This closes #115 checkstyle changes

This commit is contained in:
Clebert Suconic 2015-08-10 11:11:52 -04:00
commit 69bacc8393
3598 changed files with 180634 additions and 242802 deletions

View File

@ -32,75 +32,61 @@ import java.util.Comparator;
* execution off to the ActiveMQ Artemis cli main.
* </p>
*/
public class Artemis
{
public class Artemis {
public static void main(String[] args) throws Throwable
{
public static void main(String[] args) throws Throwable {
ArrayList<File> dirs = new ArrayList<File>();
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<URL> urls = new ArrayList<URL>();
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<File> files = new ArrayList<File>();
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<File>()
{
public int compare(File file, File file1)
{
Collections.sort(files, new Comparator<File>() {
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<URL> urls, File file)
{
try
{
private static void add(ArrayList<URL> urls, File file) {
try {
urls.add(file.toURI().toURL());
}
catch (MalformedURLException e)
{
catch (MalformedURLException e) {
e.printStackTrace();
}
}

View File

@ -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<String> args) throws Exception
{
public static Object execute(File artemisHome, File artemisInstance, List<String> 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<Action> builder(File artemisInstance)
{
private static Cli.CliBuilder<Action> builder(File artemisInstance) {
String instance = artemisInstance != null ? artemisInstance.getAbsolutePath() : System.getProperty("artemis.instance");
Cli.CliBuilder<Action> builder = Cli.<Action>builder("artemis")
.withDescription("ActiveMQ Artemis Command Line")
.withCommand(HelpAction.class)
.withCommand(Producer.class)
.withCommand(Consumer.class)
.withCommand(Browse.class)
.withDefaultCommand(HelpAction.class);
Cli.CliBuilder<Action> builder = Cli.<Action>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);
}

View File

@ -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);
}
}

View File

@ -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);

View File

@ -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;

View File

@ -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);
}

View File

@ -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();
}

View File

@ -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;
}
}

View File

@ -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();
}

View File

@ -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<String, String> filters)
{
/**
* It will create the jms configurations
*/
private void applyJMSObjects(HashMap<String, String> filters) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println();
for (String str : getQueueList())
{
for (String str : getQueueList()) {
printWriter.println(" <queue name=\"" + str + "\"/>");
}
for (String str : getTopicList())
{
for (String str : getTopicList()) {
printWriter.println(" <topic name=\"" + str + "\"/>");
}
filters.put("${jms-list.settings}", writer.toString());
}
private void performAutoTune(HashMap<String, String> filters, boolean aio, File dataFolder)
{
if (noAutoTune)
{
private void performAutoTune(HashMap<String, String> 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<PosixFilePermission>(Arrays.asList(
OWNER_READ, OWNER_WRITE, OWNER_EXECUTE,
GROUP_READ, GROUP_WRITE, GROUP_EXECUTE,
OTHERS_READ, OTHERS_EXECUTE
)));
Files.setPosixFilePermissions(file.toPath(), new HashSet<PosixFilePermission>(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<String, String> filters, boolean unixTarget) throws IOException
{
private void write(String source, HashMap<String, String> filters, boolean unixTarget) throws IOException {
write(source, new File(directory, source), filters, unixTarget);
}
private void write(String source, File target, HashMap<String, String> filters, boolean unixTarget) throws IOException
{
if (target.exists() && !force)
{
private void write(String source,
File target,
HashMap<String, String> 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<String, String> filters) throws IOException
{
private String applyFilters(String content, HashMap<String, String> filters) throws IOException {
if (filters != null)
{
for (Map.Entry<String, String> entry : filters.entrySet())
{
if (filters != null) {
for (Map.Entry<String, String> 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);
}

View File

@ -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";

View File

@ -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;
}

View File

@ -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);

View File

@ -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();

View File

@ -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();
}

View File

@ -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<ActiveMQComponent> 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();
}
}

View File

@ -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();

View File

@ -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);

View File

@ -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");
}
}

View File

@ -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<Long, JournalRecord> 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<Long, AtomicInteger> txCounters)
{
protected static AtomicInteger getCounter(final Long txID, final Map<Long, AtomicInteger> 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();
}
}

View File

@ -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<JournalFile> 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();
}
}
}

View File

@ -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<String> commands = new ArrayList<>(1);
commands.add("data");

View File

@ -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<AddressSettings> addressSettingsRepository = new HierarchicalObjectRepository<AddressSettings>();
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<PagePosition> 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<RecordInfo> records) throws Exception
{
/**
* Calculate the acks on the page system
*/
protected static PageCursorsInfo calculateCursorsInfo(List<RecordInfo> 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<PagePosition> set = cursorInfo.getCursorRecords().get(encoding.queueID);
if (set == null)
{
if (set == null) {
set = new HashSet<PagePosition>();
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<Long, Set<PagePosition>> cursorRecords = new HashMap<Long, Set<PagePosition>>();
private final Set<Long> pgTXs = new HashSet<Long>();
private final Map<Long, Set<Long>> completePages = new HashMap<Long, Set<Long>>();
public PageCursorsInfo()
{
public PageCursorsInfo() {
}
/**
* @return the pgTXs
*/
public Set<Long> getPgTXs()
{
public Set<Long> getPgTXs() {
return pgTXs;
}
/**
* @return the cursorRecords
*/
public Map<Long, Set<PagePosition>> getCursorRecords()
{
public Map<Long, Set<PagePosition>> getCursorRecords() {
return cursorRecords;
}
/**
* @return the completePages
*/
public Map<Long, Set<Long>> getCompletePages()
{
public Map<Long, Set<Long>> getCompletePages() {
return completePages;
}
public Set<Long> getCompletePages(Long queueID)
{
public Set<Long> getCompletePages(Long queueID) {
Set<Long> completePagesSet = completePages.get(queueID);
if (completePagesSet == null)
{
if (completePagesSet == null) {
completePagesSet = new HashSet<Long>();
completePages.put(queueID, completePagesSet);
}
@ -377,5 +325,4 @@ public class PrintData extends DataAbstract implements Action
}
}

View File

@ -20,12 +20,12 @@ package org.apache.activemq.artemis.cli.commands.tools;
* The constants shared by <code>org.apache.activemq.tools.XmlDataImporter</code> and
* <code>org.apache.activemq.tools.XmlDataExporter</code>.
*/
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";

View File

@ -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<RecordInfo> acks = new ArrayList<>();
List<RecordInfo> 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<RecordInfo> records1, List<RecordInfo> recordsToDelete)
{
public void failedTransaction(long transactionID,
List<RecordInfo> records1,
List<RecordInfo> 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<Long, ReferenceDescribe> map = messageRefs.get(info.id);
if (map == null)
{
if (map == null) {
HashMap<Long, ReferenceDescribe> 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<PagePosition> 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<RecordInfo> acks)
{
for (RecordInfo info : acks)
{
private void removeAcked(ArrayList<RecordInfo> acks) {
for (RecordInfo info : acks) {
AckDescribe ack = (AckDescribe) DescribeJournal.newObjectEncoding(info, null);
HashMap<Long, ReferenceDescribe> 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<PersistedType, String> 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<RecordInfo> 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<Long, PersistentQueueBindingEncoding> queueBindingEncodingEntry : queueBindings.entrySet())
{
for (Map.Entry<Long, PersistentQueueBindingEncoding> 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<PersistedType, String> jmsDestinationsKey : jmsDestinations.keySet())
{
for (Pair<PersistedType, String> 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<Long, Message> messageMapEntry : messages.entrySet())
{
for (Map.Entry<Long, Message> 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<AddressSettings> 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<String> queueNames = new ArrayList<>();
for (long queueID : queueIDs)
{
for (long queueID : queueIDs) {
PagePosition posCheck = new PagePositionImpl(pageId, messageId);
boolean acked = false;
Set<PagePosition> 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<String> queues) throws XMLStreamException
{
private void printSingleMessageAsXML(ServerMessage message, List<String> 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<String> queues) throws XMLStreamException
{
private void printMessageQueues(List<String> 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<String> extractQueueNames(HashMap<Long, ReferenceDescribe> refMap)
{
private List<String> extractQueueNames(HashMap<Long, ReferenceDescribe> refMap) {
List<String> 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 <code>javax.xml.stream.XMLStreamWriter</code> 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);

View File

@ -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<String, Object> 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<String> 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<String> queues, Message message) throws Exception
{
private void sendMessage(ArrayList<String> 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<String> queues)
{
for (int i = 0; i < reader.getAttributeCount(); i++)
{
if (XmlDataConstants.QUEUE_NAME.equals(reader.getAttributeLocalName(i)))
{
private void processMessageQueues(ArrayList<String> 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);
}

View File

@ -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<Message> 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;
}

View File

@ -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;
}

View File

@ -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;

View File

@ -24,19 +24,15 @@ import java.io.InputStreamReader;
import org.apache.activemq.artemis.utils.ConcurrentHashSet;
public class ProcessBuilder
{
public class ProcessBuilder {
static ConcurrentHashSet<Process> 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
}

View File

@ -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;
}

View File

@ -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);
}

View File

@ -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());
}

View File

@ -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;
}

View File

@ -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);
}

View File

@ -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);
}
}

View File

@ -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;
}

View File

@ -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!");
}
}

View File

@ -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);

View File

@ -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 {
}

View File

@ -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<String, ActiveMQComponent> 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<ActiveMQComponent> 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<String, ActiveMQComponent> getComponents()
{
public Map<String, ActiveMQComponent> 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<ActiveMQComponent> getComponentsByStartOrder(Map<String, ActiveMQComponent> components)
{
public ArrayList<ActiveMQComponent> getComponentsByStartOrder(Map<String, ActiveMQComponent> components) {
ArrayList<ActiveMQComponent> activeMQComponents = new ArrayList<ActiveMQComponent>();
ActiveMQComponent jmsComponent = components.get("jms");
if (jmsComponent != null)
{
if (jmsComponent != null) {
activeMQComponents.add(jmsComponent);
}
activeMQComponents.add(components.get("core"));

View File

@ -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);
}

View File

@ -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.
*/

View File

@ -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<String, Object> params = new HashMap<String, Object>();
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
}
}

View File

@ -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());
}

View File

@ -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();
}

View File

@ -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);

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -26,10 +26,11 @@ import io.netty.buffer.ByteBuf;
* Instances of it can be obtained from {@link ActiveMQBuffers} factory.
* <p>
* 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
*/

View File

@ -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 <em>self-expanding</em> 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
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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() + "]";
}

View File

@ -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<Integer, ActiveMQExceptionType> TYPE_MAP;
static
{
static {
HashMap<Integer, ActiveMQExceptionType> map = new HashMap<Integer, ActiveMQExceptionType>();
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;

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -21,17 +21,15 @@ package org.apache.activemq.artemis.api.core;
* <p>
* 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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -23,12 +23,11 @@ import java.io.Serializable;
* <p>
* This is a utility class.
*/
public final class Pair<A, B> implements Serializable
{
public final class Pair<A, B> 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<A, B> 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<A, B> 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<A, B> pother = (Pair<A, B>)other;
Pair<A, B> pother = (Pair<A, B>) 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;
}
}

View File

@ -27,10 +27,9 @@ import org.apache.activemq.artemis.utils.DataConstants;
* minimises expensive copying between String objects.
* <p>
* This object is used heavily throughout ActiveMQ Artemis for performance reasons.
*
*/
public final class SimpleString implements CharSequence, Serializable, Comparable<SimpleString>
{
public final class SimpleString implements CharSequence, Serializable, Comparable<SimpleString> {
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<SimpleString> 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;

View File

@ -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);
}

View File

@ -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;

View File

@ -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)

View File

@ -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();
}

View File

@ -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<String, ExtLogRecord> 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<String, ExtLogRecord> entry : messages.entrySet())
{
public static boolean findText(final String... text) {
for (Map.Entry<String, ExtLogRecord> 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();
}

View File

@ -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<Thread>
{
private final class ThreadCreateAction implements PrivilegedAction<Thread> {
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);

View File

@ -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();

View File

@ -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();

View File

@ -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<E> extends AbstractSet<E> implements ConcurrentSet<E>
{
public class ConcurrentHashSet<E> extends AbstractSet<E> implements ConcurrentSet<E> {
private final ConcurrentMap<E, Object> theMap;
private static final Object dummy = new Object();
public ConcurrentHashSet()
{
public ConcurrentHashSet() {
theMap = new ConcurrentHashMap<E, Object>();
}
@Override
public int size()
{
public int size() {
return theMap.size();
}
@Override
public Iterator<E> iterator()
{
public Iterator<E> 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;

View File

@ -19,12 +19,11 @@ package org.apache.activemq.artemis.utils;
import java.util.Set;
/**
*
* A ConcurrentSet
*
* @param <E> The generic class
*/
public interface ConcurrentSet<E> extends Set<E>
{
public interface ConcurrentSet<E> extends Set<E> {
boolean addIfAbsent(E o);
}

View File

@ -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;

View File

@ -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<String>
{
public class DefaultSensitiveStringCodec implements SensitiveDataCodec<String> {
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<String>
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<String>
return n.toString(16);
}
public void init(Map<String, String> params)
{
public void init(Map<String, String> 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 <classPath> 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<String>
System.out.println("Encoded password (without quotes): \"" + encode + "\"");
}
private void updateKey(String key)
{
private void updateKey(String key) {
this.internalKey = key.getBytes();
}
}

View File

@ -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<String, Class> classMap = new ConcurrentHashMap<String, Class>();
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);
}
}

View File

@ -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 <full qualified class name> is required. key/value pairs are optional
*/
public static SensitiveDataCodec<String> getCodec(String codecDesc) throws ActiveMQException
{
public static SensitiveDataCodec<String> getCodec(String codecDesc) throws ActiveMQException {
SensitiveDataCodec<String> codecInstance = null;
// semi colons
@ -49,29 +48,23 @@ public class PasswordMaskingUtil
final String codecClassName = parts[0];
// load class
codecInstance = AccessController.doPrivileged(new PrivilegedAction<SensitiveDataCodec<String>>()
{
public SensitiveDataCodec<String> run()
{
codecInstance = AccessController.doPrivileged(new PrivilegedAction<SensitiveDataCodec<String>>() {
public SensitiveDataCodec<String> run() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try
{
try {
Class<?> clazz = loader.loadClass(codecClassName);
return (SensitiveDataCodec<String>)clazz.newInstance();
return (SensitiveDataCodec<String>) clazz.newInstance();
}
catch (Exception e)
{
catch (Exception e) {
throw ActiveMQUtilBundle.BUNDLE.errorCreatingCodec(e, codecClassName);
}
}
});
if (parts.length > 1)
{
if (parts.length > 1) {
Map<String, String> props = new HashMap<String, String>();
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<String> getDefaultCodec()
{
public static SensitiveDataCodec<String> getDefaultCodec() {
return new DefaultSensitiveStringCodec();
}
}

View File

@ -16,8 +16,8 @@
*/
package org.apache.activemq.artemis.utils;
public interface ReferenceCounter
{
public interface ReferenceCounter {
int increment();
int decrement();

View File

@ -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();
}
}

Some files were not shown because too many files have changed in this diff Show More