From 8edf9da967c506a6c79b3225f9924c413270c5d6 Mon Sep 17 00:00:00 2001 From: giana Date: Sat, 14 Jun 2025 16:49:39 +0200 Subject: [PATCH] use StringBuilder instead of StringBuffer: this avoids unnecessary sync use StringBuilder best practice when concatenating avoid concatenation in logging some typo fixing --- .../amqp/client/sasl/CramMD5Mechanism.java | 19 +++--- .../amqp/client/util/PropertyUtil.java | 42 ++++++------- .../client/util/StringArrayConverter.java | 3 +- .../org/apache/activemq/console/Main.java | 6 +- .../console/command/CreateCommand.java | 60 +++++++++---------- .../store/kahadb/MessageDatabase.java | 8 +-- .../openwire/tool/CHeadersGenerator.java | 2 +- .../activemq/ra/ActiveMQActivationSpec.java | 8 +-- .../apache/activemq/tool/ReportGenerator.java | 10 +--- .../activemq/tool/AbstractJmsClient.java | 14 ++--- .../activemq/tool/JmsProducerClient.java | 33 +++------- .../region/cursors/StoreBasedCursorTest.java | 5 +- .../scheduler/ReduceMemoryFootprintTest.java | 7 +-- .../org/apache/activemq/bugs/AMQ3352Test.java | 8 +-- .../org/apache/activemq/bugs/AMQ3436Test.java | 21 ++++--- .../org/apache/activemq/bugs/AMQ4368Test.java | 18 +++--- .../org/apache/activemq/bugs/AMQ4504Test.java | 14 ++--- .../org/apache/activemq/bugs/AMQ5450Test.java | 2 +- .../bugs/CursorMemoryHighWaterMarkTest.java | 10 ++-- .../apache/activemq/bugs/JmsTimeoutTest.java | 2 +- .../apache/activemq/bugs/PfcTimeoutTest.java | 20 +++---- .../bugs/amq1095/MessageSelectorTest.java | 4 +- .../bugs/embedded/ThreadExplorer.java | 18 +++--- .../activemq/network/NetworkLoadTest.java | 27 ++++----- .../test/JmsSendReceiveTestSupport.java | 21 +++---- .../nio/NIOMaxFrameSizeCleanupTest.java | 2 +- .../transport/udp/UdpTestSupport.java | 30 ++++------ .../TopicDurableConnectStatsTest.java | 24 ++++---- .../activemq/web/RestPersistentTest.java | 4 +- .../org/apache/activemq/web/RestTest.java | 6 +- .../apache/activemq/benchmark/Producer.java | 4 +- 31 files changed, 203 insertions(+), 249 deletions(-) diff --git a/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/sasl/CramMD5Mechanism.java b/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/sasl/CramMD5Mechanism.java index 7ad14e434dc..fbd85a27e14 100644 --- a/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/sasl/CramMD5Mechanism.java +++ b/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/sasl/CramMD5Mechanism.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.transport.amqp.client.sasl; -import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -24,6 +23,8 @@ import javax.crypto.spec.SecretKeySpec; import javax.security.sasl.SaslException; +import static java.nio.charset.StandardCharsets.US_ASCII; + /** * Implements the SASL PLAIN authentication Mechanism. * @@ -31,7 +32,6 @@ */ public class CramMD5Mechanism extends AbstractMechanism { - private static final String ASCII = "ASCII"; private static final String HMACMD5 = "HMACMD5"; private boolean sentResponse; @@ -54,16 +54,17 @@ public byte[] getInitialResponse() { public byte[] getChallengeResponse(byte[] challenge) throws SaslException { if (!sentResponse && challenge != null && challenge.length != 0) { try { - SecretKeySpec key = new SecretKeySpec(getPassword().getBytes(ASCII), HMACMD5); + SecretKeySpec key = new SecretKeySpec(getPassword().getBytes(US_ASCII), HMACMD5); Mac mac = Mac.getInstance(HMACMD5); mac.init(key); byte[] bytes = mac.doFinal(challenge); - StringBuffer hash = new StringBuffer(getUsername()); + StringBuilder hash = new StringBuilder((bytes.length * 2) + 64); + hash.append(getUsername()); hash.append(' '); - for (int i = 0; i < bytes.length; i++) { - String hex = Integer.toHexString(0xFF & bytes[i]); + for (byte aByte : bytes) { + String hex = Integer.toHexString(0xFF & aByte); if (hex.length() == 1) { hash.append('0'); } @@ -71,9 +72,7 @@ public byte[] getChallengeResponse(byte[] challenge) throws SaslException { } sentResponse = true; - return hash.toString().getBytes(ASCII); - } catch (UnsupportedEncodingException e) { - throw new SaslException("Unable to utilise required encoding", e); + return hash.toString().getBytes(US_ASCII); } catch (InvalidKeyException e) { throw new SaslException("Unable to utilise key", e); } catch (NoSuchAlgorithmException e) { @@ -86,6 +85,6 @@ public byte[] getChallengeResponse(byte[] challenge) throws SaslException { @Override public boolean isApplicable(String username, String password) { - return username != null && username.length() > 0 && password != null && password.length() > 0; + return username != null && !username.isEmpty() && password != null && !password.isEmpty(); } } diff --git a/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/util/PropertyUtil.java b/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/util/PropertyUtil.java index 9be74978a03..4d9f39e0986 100644 --- a/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/util/PropertyUtil.java +++ b/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/util/PropertyUtil.java @@ -19,13 +19,13 @@ import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; -import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; @@ -85,7 +85,7 @@ public static URI replaceQuery(URI uri, String query) throws URISyntaxException if (questionMark > 0) { schemeSpecificPart = schemeSpecificPart.substring(0, questionMark); } - if (query != null && query.length() > 0) { + if (query != null && !query.isEmpty()) { schemeSpecificPart += "?" + query; } return new URI(uri.getScheme(), schemeSpecificPart, uri.getFragment()); @@ -116,27 +116,23 @@ public static URI eraseQuery(URI uri) throws URISyntaxException { * * @throws URISyntaxException if the given URI is invalid. */ - public static String createQueryString(Map options) throws URISyntaxException { - try { - if (options.size() > 0) { - StringBuffer rc = new StringBuffer(); - boolean first = true; - for (Entry entry : options.entrySet()) { - if (first) { - first = false; - } else { - rc.append("&"); - } - rc.append(URLEncoder.encode(entry.getKey(), "UTF-8")); - rc.append("="); - rc.append(URLEncoder.encode((String) entry.getValue(), "UTF-8")); + public static String createQueryString(Map options) { + if (!options.isEmpty()) { + StringBuilder rc = new StringBuilder(); + boolean first = true; + for (Entry entry : options.entrySet()) { + if (first) { + first = false; + } else { + rc.append("&"); } - return rc.toString(); - } else { - return ""; + rc.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)); + rc.append("="); + rc.append(URLEncoder.encode((String) entry.getValue(), StandardCharsets.UTF_8)); } - } catch (UnsupportedEncodingException e) { - throw (URISyntaxException) new URISyntaxException(e.toString(), "Invalid encoding").initCause(e); + return rc.toString(); + } else { + return ""; } } @@ -196,8 +192,8 @@ public static Map parseQuery(String queryString) throws Exceptio for (int i = 0; i < parameters.length; i++) { int p = parameters[i].indexOf("="); if (p >= 0) { - String name = URLDecoder.decode(parameters[i].substring(0, p), "UTF-8"); - String value = URLDecoder.decode(parameters[i].substring(p + 1), "UTF-8"); + String name = URLDecoder.decode(parameters[i].substring(0, p), StandardCharsets.UTF_8); + String value = URLDecoder.decode(parameters[i].substring(p + 1), StandardCharsets.UTF_8); rc.put(name, value); } else { rc.put(parameters[i], null); diff --git a/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/util/StringArrayConverter.java b/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/util/StringArrayConverter.java index e5951058266..96003d6a361 100644 --- a/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/util/StringArrayConverter.java +++ b/activemq-amqp/src/test/java/org/apache/activemq/transport/amqp/client/util/StringArrayConverter.java @@ -54,7 +54,8 @@ public static String convertToString(String[] value) { return null; } - StringBuffer result = new StringBuffer(String.valueOf(value[0])); + StringBuilder result = new StringBuilder(value.length * 2); + result.append(value[0]); for (int i = 1; i < value.length; i++) { result.append(",").append(value[i]); } diff --git a/activemq-console/src/main/java/org/apache/activemq/console/Main.java b/activemq-console/src/main/java/org/apache/activemq/console/Main.java index a6d507accaf..71251729e80 100644 --- a/activemq-console/src/main/java/org/apache/activemq/console/Main.java +++ b/activemq-console/src/main/java/org/apache/activemq/console/Main.java @@ -143,7 +143,7 @@ private static int printClassLoaderTree(ClassLoader cl) { depth = printClassLoaderTree(cl.getParent()) + 1; } - StringBuffer indent = new StringBuffer(); + StringBuilder indent = new StringBuilder(depth * 2); for (int i = 0; i < depth; i++) { indent.append(" "); } @@ -270,7 +270,7 @@ public void addExtensionDirectory(File directory) { } public void addClassPathList(String fileList) { - if (fileList != null && fileList.length() > 0) { + if (fileList != null && !fileList.isEmpty()) { StringTokenizer tokenizer = new StringTokenizer(fileList, File.pathSeparator); while (tokenizer.hasMoreTokens()) { addClassPath(new File(tokenizer.nextToken())); @@ -335,7 +335,7 @@ public int compare(File f1, File f2) { } } - URL u[] = new URL[urls.size()]; + URL[] u = new URL[urls.size()]; urls.toArray(u); classLoader = new URLClassLoader(u, classLoader); } diff --git a/activemq-console/src/main/java/org/apache/activemq/console/command/CreateCommand.java b/activemq-console/src/main/java/org/apache/activemq/console/command/CreateCommand.java index c1c8685f45b..44bf8f8619f 100644 --- a/activemq-console/src/main/java/org/apache/activemq/console/command/CreateCommand.java +++ b/activemq-console/src/main/java/org/apache/activemq/console/command/CreateCommand.java @@ -233,7 +233,7 @@ private void copyFile(File from, File dest) throws IOException { private void copyConfDirectory(File from, File dest) throws IOException { if (from.isDirectory()) { - String files[] = from.list(); + String[] files = from.list(); for (String file : files) { File srcFile = new File(from, file); @@ -271,36 +271,34 @@ private String resolveParam(String paramName, String paramValue, String target) private String getUnixActivemqData() { - StringBuffer res = new StringBuffer(); - res.append("#!/bin/sh\n\n"); - res.append("## Figure out the ACTIVEMQ_BASE from the directory this script was run from\n"); - res.append("PRG=\"$0\"\n"); - res.append("progname=`basename \"$0\"`\n"); - res.append("saveddir=`pwd`\n"); - res.append("# need this for relative symlinks\n"); - res.append("dirname_prg=`dirname \"$PRG\"`\n"); - res.append("cd \"$dirname_prg\"\n"); - res.append("while [ -h \"$PRG\" ] ; do\n"); - res.append(" ls=`ls -ld \"$PRG\"`\n"); - res.append(" link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n"); - res.append(" if expr \"$link\" : '.*/.*' > /dev/null; then\n"); - res.append(" PRG=\"$link\"\n"); - res.append(" else\n"); - res.append(" PRG=`dirname \"$PRG\"`\"/$link\"\n"); - res.append(" fi\n"); - res.append("done\n"); - res.append("ACTIVEMQ_BASE=`dirname \"$PRG\"`/..\n"); - res.append("cd \"$saveddir\"\n\n"); - res.append("ACTIVEMQ_BASE=`cd \"$ACTIVEMQ_BASE\" && pwd`\n\n"); - res.append("## Enable remote debugging\n"); - res.append("#export ACTIVEMQ_DEBUG_OPTS=\"-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005\"\n\n"); - res.append("## Add system properties for this instance here (if needed), e.g\n"); - res.append("#export ACTIVEMQ_OPTS_MEMORY=\"-Xms256M -Xmx1G\"\n"); - res.append("#export ACTIVEMQ_OPTS=\"$ACTIVEMQ_OPTS_MEMORY -Dorg.apache.activemq.UseDedicatedTaskRunner=true -Djava.util.logging.config.file=logging.properties\"\n\n"); - res.append("export ACTIVEMQ_HOME=${activemq.home}\n"); - res.append("export ACTIVEMQ_BASE=$ACTIVEMQ_BASE\n\n"); - res.append("${ACTIVEMQ_HOME}/bin/activemq \"$@\""); - return res.toString(); + return "#!/bin/sh\n\n" + + "## Figure out the ACTIVEMQ_BASE from the directory this script was run from\n" + + "PRG=\"$0\"\n" + + "progname=`basename \"$0\"`\n" + + "saveddir=`pwd`\n" + + "# need this for relative symlinks\n" + + "dirname_prg=`dirname \"$PRG\"`\n" + + "cd \"$dirname_prg\"\n" + + "while [ -h \"$PRG\" ] ; do\n" + + " ls=`ls -ld \"$PRG\"`\n" + + " link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n" + + " if expr \"$link\" : '.*/.*' > /dev/null; then\n" + + " PRG=\"$link\"\n" + + " else\n" + + " PRG=`dirname \"$PRG\"`\"/$link\"\n" + + " fi\n" + + "done\n" + + "ACTIVEMQ_BASE=`dirname \"$PRG\"`/..\n" + + "cd \"$saveddir\"\n\n" + + "ACTIVEMQ_BASE=`cd \"$ACTIVEMQ_BASE\" && pwd`\n\n" + + "## Enable remote debugging\n" + + "#export ACTIVEMQ_DEBUG_OPTS=\"-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005\"\n\n" + + "## Add system properties for this instance here (if needed), e.g\n" + + "#export ACTIVEMQ_OPTS_MEMORY=\"-Xms256M -Xmx1G\"\n" + + "#export ACTIVEMQ_OPTS=\"$ACTIVEMQ_OPTS_MEMORY -Dorg.apache.activemq.UseDedicatedTaskRunner=true -Djava.util.logging.config.file=logging.properties\"\n\n" + + "export ACTIVEMQ_HOME=${activemq.home}\n" + + "export ACTIVEMQ_BASE=$ACTIVEMQ_BASE\n\n" + + "${ACTIVEMQ_HOME}/bin/activemq \"$@\""; } } diff --git a/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java b/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java index dbab306fc7d..3fd0adad02d 100644 --- a/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java +++ b/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java @@ -191,7 +191,7 @@ public void read(DataInput is) throws IOException { openwireVersion = OpenWireFormat.DEFAULT_LEGACY_VERSION; } - LOG.info("KahaDB is version " + version); + LOG.info("KahaDB is version {}", version); } public void write(DataOutput os) throws IOException { @@ -381,7 +381,7 @@ public void execute(Transaction tx) throws IOException { private void startCheckpoint() { if (checkpointInterval == 0 && cleanupInterval == 0) { - LOG.info("periodic checkpoint/cleanup disabled, will occur on clean " + (getCleanupOnStop() ? "shutdown/" : "") + "restart"); + LOG.info("periodic checkpoint/cleanup disabled, will occur on clean {}restart", getCleanupOnStop() ? "shutdown/" : ""); return; } synchronized (schedulerLock) { @@ -463,7 +463,7 @@ public void open() throws IOException { try { loadPageFile(); } catch (Throwable t) { - LOG.warn("Index corrupted. Recovering the index through journal replay. Cause:" + t); + LOG.warn("Index corrupted. Recovering the index through journal replay. Cause", t); if (LOG.isDebugEnabled()) { LOG.debug("Index load failure", t); } @@ -631,7 +631,7 @@ public void track(Operation operation) { @Override public String toString() { - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); buffer.append(location).append(";").append(id).append(";\n"); for (Entry op : destinationOpCount.entrySet()) { buffer.append(op.getKey()).append('+').append(op.getValue().add).append(',').append('-').append(op.getValue().remove).append(';'); diff --git a/activemq-openwire-generator/src/main/java/org/apache/activemq/openwire/tool/CHeadersGenerator.java b/activemq-openwire-generator/src/main/java/org/apache/activemq/openwire/tool/CHeadersGenerator.java index 627481926ca..830a7fd088e 100644 --- a/activemq-openwire-generator/src/main/java/org/apache/activemq/openwire/tool/CHeadersGenerator.java +++ b/activemq-openwire-generator/src/main/java/org/apache/activemq/openwire/tool/CHeadersGenerator.java @@ -74,7 +74,7 @@ protected void generateLicence(PrintWriter out) { } String changeCase(String value) { - StringBuffer b = new StringBuffer(); + StringBuilder b = new StringBuilder(); char[] cs = value.toCharArray(); for (int i = 0; i < cs.length; i++) { char c = cs[i]; diff --git a/activemq-ra/src/main/java/org/apache/activemq/ra/ActiveMQActivationSpec.java b/activemq-ra/src/main/java/org/apache/activemq/ra/ActiveMQActivationSpec.java index ad6bcabd6ce..d7ec3a413a3 100644 --- a/activemq-ra/src/main/java/org/apache/activemq/ra/ActiveMQActivationSpec.java +++ b/activemq-ra/src/main/java/org/apache/activemq/ra/ActiveMQActivationSpec.java @@ -132,12 +132,12 @@ public void validate() throws InvalidPropertyException { e.printStackTrace(); } - if (propsNotSet.size() > 0) { - StringBuffer b = new StringBuffer(); + if (!propsNotSet.isEmpty()) { + StringBuilder b = new StringBuilder(); b.append("Invalid settings:"); - for (Iterator iter = errorMessages.iterator(); iter.hasNext();) { + for (String errorMessage : errorMessages) { b.append(" "); - b.append(iter.next()); + b.append(errorMessage); } InvalidPropertyException e = new InvalidPropertyException(b.toString()); final PropertyDescriptor[] descriptors = propsNotSet.toArray(new PropertyDescriptor[propsNotSet.size()]); diff --git a/activemq-tooling/activemq-memtest-maven-plugin/src/main/java/org/apache/activemq/tool/ReportGenerator.java b/activemq-tooling/activemq-memtest-maven-plugin/src/main/java/org/apache/activemq/tool/ReportGenerator.java index 984cb6eee38..a02993c9379 100644 --- a/activemq-tooling/activemq-memtest-maven-plugin/src/main/java/org/apache/activemq/tool/ReportGenerator.java +++ b/activemq-tooling/activemq-memtest-maven-plugin/src/main/java/org/apache/activemq/tool/ReportGenerator.java @@ -114,14 +114,8 @@ protected void endTestResult() { } protected void writeWithIndent(int indent, String result) { - StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < indent; ++i) { - buffer.append(" "); - } - - buffer.append(result); - writer.println(buffer.toString()); + String buffer = " ".repeat(Math.max(0, indent)) + result; + writer.println(buffer); } public PrintWriter getWriter() { diff --git a/activemq-tooling/activemq-perf-maven-plugin/src/main/java/org/apache/activemq/tool/AbstractJmsClient.java b/activemq-tooling/activemq-perf-maven-plugin/src/main/java/org/apache/activemq/tool/AbstractJmsClient.java index 0fbaaa7ba3c..a9d80ad4867 100644 --- a/activemq-tooling/activemq-perf-maven-plugin/src/main/java/org/apache/activemq/tool/AbstractJmsClient.java +++ b/activemq-tooling/activemq-perf-maven-plugin/src/main/java/org/apache/activemq/tool/AbstractJmsClient.java @@ -90,7 +90,7 @@ public Connection getConnection() throws JMSException { if (jmsConnection == null) { jmsConnection = factory.createConnection(); jmsConnection.setClientID(getClientName()); - LOG.info("Creating JMS Connection: Provider=" + getClient().getJmsProvider() + ", JMS Spec=" + getClient().getJmsVersion()); + LOG.info("Creating JMS Connection: Provider={}, JMS Spec={}", getClient().getJmsProvider(), getClient().getJmsVersion()); } return jmsConnection; } @@ -142,7 +142,7 @@ public Destination[] createDestinations(int destCount) throws JMSException { } private String join(String[] stings, String separator) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < stings.length; i++) { if (i > 0) { sb.append(separator); @@ -174,21 +174,21 @@ protected Destination createCompositeDestination(String destName, int destCount) protected Destination createCompositeDestination(byte destinationType, String destName, int destCount) throws JMSException { String simpleName = getSimpleName(destName); - String compDestName = ""; + StringBuilder compDestName = new StringBuilder(destCount * (simpleName.length() + 4)); for (int i = 0; i < destCount; i++) { if (i > 0) { - compDestName += ","; + compDestName.append(","); } - compDestName += withDestinationSuffix(simpleName, i, destCount); + compDestName.append(withDestinationSuffix(simpleName, i, destCount)); } LOG.info("Creating composite destination: {}", compDestName); Destination destination; Session session = getSession(); if (destinationType == ActiveMQDestination.TOPIC_TYPE) { - destination = session.createTopic(compDestName); + destination = session.createTopic(compDestName.toString()); } else if (destinationType == ActiveMQDestination.QUEUE_TYPE) { - destination = session.createQueue(compDestName); + destination = session.createQueue(compDestName.toString()); } else { throw new UnsupportedOperationException( "Cannot create composite destinations using temporary queues or topics."); diff --git a/activemq-tooling/activemq-perf-maven-plugin/src/main/java/org/apache/activemq/tool/JmsProducerClient.java b/activemq-tooling/activemq-perf-maven-plugin/src/main/java/org/apache/activemq/tool/JmsProducerClient.java index 4f6a89bd5fd..7003aa67ab3 100644 --- a/activemq-tooling/activemq-perf-maven-plugin/src/main/java/org/apache/activemq/tool/JmsProducerClient.java +++ b/activemq-tooling/activemq-perf-maven-plugin/src/main/java/org/apache/activemq/tool/JmsProducerClient.java @@ -91,18 +91,9 @@ public void sendCountBasedMessages(long messageCount) throws JMSException { try { getConnection().start(); if (client.getMsgFileName() != null) { - LOG.info("Starting to publish " + - messageCount + - " messages from file " + - client.getMsgFileName() - ); + LOG.info("Starting to publish {} messages from file {}", messageCount, client.getMsgFileName()); } else { - LOG.info("Starting to publish " + - messageCount + - " messages of size " + - client.getMessageSize() + - " byte(s)." - ); + LOG.info("Starting to publish {} messages of size {} byte(s).", messageCount, client.getMessageSize()); } // Send one type of message only, avoiding the creation of different messages on sending @@ -180,17 +171,9 @@ public void sendTimeBasedMessages(long duration) throws JMSException { try { getConnection().start(); if (client.getMsgFileName() != null) { - LOG.info("Starting to publish messages from file " + - client.getMsgFileName() + - " for " + - duration + - " ms"); + LOG.info("Starting to publish messages from file {} for {} ms", client.getMsgFileName(), duration); } else { - LOG.info("Starting to publish " + - client.getMessageSize() + - " byte(s) messages for " + - duration + - " ms"); + LOG.info("Starting to publish {} byte(s) messages for {} ms", client.getMessageSize(), duration); } // Send one type of message only, avoiding the creation of different messages on sending if (!client.isCreateNewMsg()) { @@ -268,10 +251,10 @@ public MessageProducer createJmsProducer() throws JMSException { public MessageProducer createJmsProducer(Destination dest) throws JMSException { jmsProducer = getSession().createProducer(dest); if (client.getDeliveryMode().equalsIgnoreCase(JmsProducerProperties.DELIVERY_MODE_PERSISTENT)) { - LOG.info("Creating producer to: " + dest.toString() + " with persistent delivery."); + LOG.info("Creating producer to: {} with persistent delivery.", dest.toString()); jmsProducer.setDeliveryMode(DeliveryMode.PERSISTENT); } else if (client.getDeliveryMode().equalsIgnoreCase(JmsProducerProperties.DELIVERY_MODE_NON_PERSISTENT)) { - LOG.info("Creating producer to: " + dest.toString() + " with non-persistent delivery."); + LOG.info("Creating producer to: {} with non-persistent delivery.", dest.toString()); jmsProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } else { LOG.warn("Unknown deliveryMode value. Defaulting to non-persistent."); @@ -350,7 +333,7 @@ protected String buildText(String text, int size) { protected void sleep() { if (client.getSendDelay() > 0) { try { - LOG.trace("Sleeping for " + client.getSendDelay() + " milliseconds"); + LOG.trace("Sleeping for {} milliseconds", client.getSendDelay()); Thread.sleep(client.getSendDelay()); } catch (java.lang.InterruptedException ex) { LOG.warn(ex.getMessage()); @@ -376,7 +359,7 @@ protected TextMessage loadJmsMessage() throws JMSException { } // try to load file - StringBuffer payload = new StringBuffer(); + StringBuilder payload = new StringBuilder(); try(FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr)) { String tmp = null; diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java index e7d8f6b8962..916459827dd 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java @@ -102,8 +102,9 @@ protected void configureBroker(long memoryLimit, long systemLimit) throws Except } protected String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(messageSize); - buffer.append("Message: " + index + " sent at: " + new Date()); + StringBuilder buffer = new StringBuilder(messageSize); + buffer.append("Message: ").append(index) + .append(" sent at: ").append(new Date()); if (buffer.length() > messageSize) { return buffer.substring(0, messageSize); } diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/ReduceMemoryFootprintTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/ReduceMemoryFootprintTest.java index 0f09a6f160b..3d5ba8b27b5 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/ReduceMemoryFootprintTest.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/ReduceMemoryFootprintTest.java @@ -140,12 +140,7 @@ public void testPropertyLostScheduled() throws Exception { } private String createMessageText() { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < 50; i++) { - buffer.append("1234567890"); - } - - return buffer.toString(); + return "1234567890".repeat(50); } private Message consumeMessages(Connection connection) { diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3352Test.java b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3352Test.java index 132fca9f0c6..8863433965c 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3352Test.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3352Test.java @@ -59,17 +59,15 @@ public void verifyEnqueueLargeNumWithStateTracker() throws Exception { producer.setDisableMessageID(true); producer.setDisableMessageTimestamp(true); - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); for (int i=0;i<1024;i++) { - buffer.append(String.valueOf(Math.random())); + buffer.append(Math.random()); } String payload = buffer.toString(); for (int i=0; i<10000; i++) { - StringBuffer buff = new StringBuffer("x"); - buff.append(payload); - producer.send(session.createTextMessage(buff.toString())); + producer.send(session.createTextMessage("x" + payload)); } } } diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3436Test.java b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3436Test.java index 4d21417e83a..622d5ab2874 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3436Test.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ3436Test.java @@ -131,12 +131,12 @@ public void testPriorityWhenConsumerCreatedBeforeProduction() throws Exception { producer.close(); // *************************************************** - // If we create the consumer here instead of above, the + // If we create the consumer here instead of above, // the messages will be consumed in priority order // *************************************************** //consumer = (ActiveMQMessageConsumer) consumerSession.createConsumer(dest); - // Consume all of the messages we produce using a listener. + // Consume all the messages we produce using a listener. // Don't exit until we get all the messages. final CountDownLatch latch = new CountDownLatch(messageCount); final StringBuffer failureMessage = new StringBuffer(); @@ -150,11 +150,11 @@ public void onMessage(Message msg) { try { int currentPriority = msg.getJMSPriority(); - LOG.debug(currentPriority + "<=" + lowestPrioritySeen); + LOG.debug("{}<={}", currentPriority, lowestPrioritySeen); // Ignore the first message priority since it is prefetched // and is out of order by design - if (firstMessage == true) { + if (firstMessage) { firstMessage = false; LOG.debug("Ignoring first message since it was prefetched"); @@ -167,9 +167,12 @@ public void onMessage(Message msg) { lowestPrioritySeen = currentPriority; } if (lowestPrioritySeen < currentPriority) { - failureMessage.append("Incorrect priority seen (Lowest Priority = " + lowestPrioritySeen - + " Current Priority = " + currentPriority + ")" - + System.getProperty("line.separator")); + failureMessage.append("Incorrect priority seen (Lowest Priority = ") + .append(lowestPrioritySeen) + .append(" Current Priority = ") + .append(currentPriority) + .append(")") + .append(System.lineSeparator()); } } @@ -177,7 +180,7 @@ public void onMessage(Message msg) { e.printStackTrace(); } finally { latch.countDown(); - LOG.debug("Messages remaining = " + latch.getCount()); + LOG.debug("Messages remaining = {}", latch.getCount()); } } }); @@ -196,7 +199,7 @@ public void onMessage(Message msg) { consumerConnection.close(); // Report the failure if found - if (failureMessage.length() > 0) { + if (!failureMessage.isEmpty()) { Assert.fail(failureMessage.toString()); } } diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4368Test.java b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4368Test.java index a20b9a5d1b3..9afcd5d247c 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4368Test.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4368Test.java @@ -102,7 +102,7 @@ abstract class Client implements Runnable { } public void start() { - LOG.info("Starting: " + name); + LOG.info("Starting: {}", name); new Thread(this, name).start(); } @@ -117,6 +117,7 @@ public void stop() throws InterruptedException { connection.close(); doneLatch.await(); } catch (Exception e) { + LOG.warn("Exception occurred", e); } } } @@ -133,11 +134,12 @@ public void run() { try { connection.close(); } catch (JMSException ignore) { + LOG.warn("exception ignored", ignore); } - LOG.info("Stopped: " + name); + LOG.info("Stopped: {}", name); } } catch (Exception e) { - e.printStackTrace(); + LOG.warn("exception occurred", e); done.set(true); } finally { doneLatch.countDown(); @@ -162,11 +164,11 @@ class ProducingClient extends Client { } private String createMessage() { - StringBuffer stringBuffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (long i = 0; i < 1000000; i++) { - stringBuffer.append("1234567890"); + sb.append("1234567890"); } - return stringBuffer.toString(); + return sb.toString(); } @Override @@ -178,7 +180,7 @@ protected void work() throws Exception { producer.send(session.createTextMessage(data)); long i = size.incrementAndGet(); if ((i % 1000) == 0) { - LOG.info("produced " + i + "."); + LOG.info("produced {}.", i); } } } @@ -234,7 +236,7 @@ public boolean isSatisified() throws Exception { } }); long size = listener1.size.get(); - LOG.info("Listener 1: consumed: " + (size - lastSize.get())); + LOG.info("Listener 1: consumed: {}", size - lastSize.get()); assertTrue("No messages received on iteration: " + i, size > lastSize.get()); lastSize.set(size); } diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4504Test.java b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4504Test.java index 864fa3a6abd..8e5af597414 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4504Test.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4504Test.java @@ -53,15 +53,15 @@ public void testCompositeDestConsumer() throws Exception { final int numDests = 20; final int numMessages = 200; - StringBuffer stringBuffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i=0; i adapters = new ArrayList(); if (compositeMatch) { - StringBuffer compositeDestBuf = new StringBuffer(); + StringBuilder compositeDestBuf = new StringBuilder(DESTS.length * 3); for (int i=1; i<=DESTS.length;i++) { for (int j=0;j 10000; i++) { - stringBuffer.append("0123456789"); + sb.append("0123456789"); } - return stringBuffer.toString(); + return sb.toString(); } - private void consume(String queue, int messageCount) throws Exception { Connection con = connectionFactory.createConnection(); diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/JmsTimeoutTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/JmsTimeoutTest.java index cc8d2f244e3..778ae2b81ed 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/JmsTimeoutTest.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/JmsTimeoutTest.java @@ -146,7 +146,7 @@ protected ConnectionFactory createConnectionFactory() throws Exception { } protected String createMessageText() { - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); buffer.append(""); for (int i = buffer.length(); i < messageSize; i++) { buffer.append('X'); diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/PfcTimeoutTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/PfcTimeoutTest.java index 556b5d298eb..0f670c845e2 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/PfcTimeoutTest.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/PfcTimeoutTest.java @@ -135,8 +135,8 @@ public void testTransactedSendWithTimeoutRollbackUsage() throws Exception { long memoryUsage = queueView.getCursorMemoryUsage(); - LOG.info("queueSize after test = " + queueSize); - LOG.info("memoryUsage after test = " + memoryUsage); + LOG.info("queueSize after test = {}", queueSize); + LOG.info("memoryUsage after test = {}", memoryUsage); assertEquals("queue size after test ", 0, queueSize); assertEquals("memory size after test ", 0, memoryUsage); @@ -174,13 +174,13 @@ private int sendMessages(final BrokerService broker, final CountDownLatch gotTim } - LOG.info(" Finished after producing : " + numberOfMessageSent); + LOG.info(" Finished after producing : {}", numberOfMessageSent); return numberOfMessageSent; } catch (Exception ex) { LOG.info("Exception received producing ", ex); - LOG.info("finishing after exception :" + numberOfMessageSent); + LOG.info("finishing after exception :{}", numberOfMessageSent); LOG.info("rolling back current transaction "); gotTimeoutException.countDown(); @@ -196,13 +196,7 @@ private int sendMessages(final BrokerService broker, final CountDownLatch gotTim } private String createTextMessage(int size) { - StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < size; i++) { - buffer.append("9"); - } - - return buffer.toString(); + return "9".repeat(Math.max(0, size)); } @@ -233,13 +227,13 @@ private int consumeMessages(BrokerService broker, int messageCount) throws Excep numberOfMessageConsumed++; } - LOG.info(" Finished after consuming : " + numberOfMessageConsumed); + LOG.info(" Finished after consuming : {}", numberOfMessageConsumed); return numberOfMessageConsumed; } catch (Exception ex) { LOG.info("Exception received producing ", ex); - LOG.info("finishing after exception :" + numberOfMessageConsumed); + LOG.info("finishing after exception :{}", numberOfMessageConsumed); return numberOfMessageConsumed; diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/MessageSelectorTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/MessageSelectorTest.java index 49c76d8d167..33f09fe7341 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/MessageSelectorTest.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/amq1095/MessageSelectorTest.java @@ -153,7 +153,7 @@ private void runMessageSelectorTest(final boolean isDurableSubscriber) msg1 = (TextMessage) consumer1.receive(RECEIVE_TIMEOUT); if (msg1 != null) { - final StringBuffer msg = new StringBuffer("The consumer read a message that was left over from a former ActiveMQ broker run."); + final StringBuilder msg = new StringBuilder("The consumer read a message that was left over from a former ActiveMQ broker run."); propertyValue = msg1.getIntProperty(PROPERTY_CONSUMER); contents = msg1.getText(); if (propertyValue != 1) // Is the property value as expected? @@ -167,7 +167,7 @@ private void runMessageSelectorTest(final boolean isDurableSubscriber) msg2 = (TextMessage) consumer2.receive(RECEIVE_TIMEOUT); if (msg2 != null) { - final StringBuffer msg = new StringBuffer("The consumer read a message that was left over from a former ActiveMQ broker run."); + final StringBuilder msg = new StringBuilder("The consumer read a message that was left over from a former ActiveMQ broker run."); propertyValue = msg2.getIntProperty(PROPERTY_CONSUMER); contents = msg2.getText(); if (propertyValue != 2) // Is the property value as expected? diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/ThreadExplorer.java b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/ThreadExplorer.java index cc6cbf37453..1640d930f55 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/ThreadExplorer.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/bugs/embedded/ThreadExplorer.java @@ -30,7 +30,7 @@ public static Thread[] listThreads() { int nThreads = Thread.activeCount(); - Thread ret[] = new Thread[nThreads]; + Thread[] ret = new Thread[nThreads]; Thread.enumerate(ret); @@ -70,7 +70,7 @@ public static int kill(String threadName, boolean isStarredExp, String motivatio String me = "ThreadExplorer.kill: "; if (logger.isDebugEnabled()) { - logger.debug("Entering " + me + " with " + threadName + " isStarred: " + isStarredExp); + logger.debug("Entering {} with {} isStarred: {}", me, threadName, isStarredExp); } int ret = 0; Pattern mypattern = null; @@ -101,7 +101,7 @@ public static int kill(String threadName, boolean isStarredExp, String motivatio if (matches && (Thread.currentThread() != thread) && !thread.getName().equals("main")) { if (logger.isInfoEnabled()) - logger.info("Killing thread named [" + thread.getName() + "]"); // , removing its uncaught + logger.info("Killing thread named [{}]", thread.getName()); // , removing its uncaught // exception handler to // avoid ThreadDeath // exception tracing @@ -128,22 +128,24 @@ public static int kill(String threadName, boolean isStarredExp, String motivatio public static String show(String title) { - StringBuffer out = new StringBuffer(); + StringBuilder out = new StringBuilder(); Thread[] threadArray = ThreadExplorer.listThreads(); - out.append(title + "\n"); + out.append(title).append("\n"); for (int i = 0; i < threadArray.length; i++) { Thread thread = threadArray[i]; if (thread != null) { - out.append("* [" + thread.getName() + "] " + (thread.isDaemon() ? "(Daemon)" : "") - + " Group: " + (thread.getThreadGroup() != null ? thread.getThreadGroup().getName() : "") + "\n"); + out.append("* [").append(thread.getName()).append("] ") + .append(thread.isDaemon() ? "(Daemon)" : "").append(" Group: ") + .append(thread.getThreadGroup() != null ? thread.getThreadGroup().getName() : "") + .append("\n"); } else { - out.append("* ThreadDeath: " + thread + "\n"); + out.append("* ThreadDeath: ").append(thread).append("\n"); } } diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java index 81bc03166af..4d9b9e09f2f 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java @@ -57,7 +57,7 @@ * * If the network bridges gets stuck at any point subsequent queues will not get messages. This test * samples the production and consumption stats every second and if the flow of messages - * get stuck then this tast fails. The test monitors the flow of messages for 1 min. + * get stuck then this test fails. The test monitors the flow of messages for 1 min. * * @author chirino */ @@ -126,7 +126,7 @@ protected void setUp() throws Exception { groupId = "network-load-test-"+System.currentTimeMillis(); brokers = new BrokerService[BROKER_COUNT]; for (int i = 0; i < brokers.length; i++) { - LOG.info("Starting broker: "+i); + LOG.info("Starting broker: {}", i); brokers[i] = createBroker(i); brokers[i].start(); } @@ -137,7 +137,7 @@ protected void setUp() throws Exception { forwardingClients = new ForwardingClient[BROKER_COUNT-1]; for (int i = 0; i < forwardingClients.length; i++) { - LOG.info("Starting fowarding client "+i); + LOG.info("Starting forwarding client {}", i); forwardingClients[i] = new ForwardingClient(i, i+1); forwardingClients[i].start(); } @@ -145,11 +145,11 @@ protected void setUp() throws Exception { protected void tearDown() throws Exception { for (int i = 0; i < forwardingClients.length; i++) { - LOG.info("Stoping fowarding client "+i); + LOG.info("Stoping forwarding client {}", i); forwardingClients[i].close(); } for (int i = 0; i < brokers.length; i++) { - LOG.info("Stoping broker "+i); + LOG.info("Stoping broker {}", i); brokers[i].stop(); } } @@ -232,7 +232,7 @@ public void testRequestReply() throws Exception { final AtomicLong receivedMessages = new AtomicLong(); final AtomicBoolean done = new AtomicBoolean(); - // Setup the consumer.. + // Set up the consumer... consumer.setMessageListener(new MessageListener() { public void onMessage(Message msg) { ActiveMQTextMessage m = (ActiveMQTextMessage) msg; @@ -271,8 +271,8 @@ public void run() { } private String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(MESSAGE_SIZE); - buffer.append(index + " on " + new Date() + " ..."); + StringBuilder buffer = new StringBuilder(MESSAGE_SIZE); + buffer.append(index).append(" on ").append(new Date()).append(" ..."); if (buffer.length() > MESSAGE_SIZE) { return buffer.substring(0, MESSAGE_SIZE); } @@ -287,7 +287,7 @@ private String createMessageText(int index) { // Give the forwarding clients a chance to get going and fill the down - // stream broker queues.. + // stream broker queues... Thread.sleep(BROKER_COUNT*200); for (int i = 0; i < SAMPLES; i++) { @@ -305,9 +305,9 @@ private String createMessageText(int index) { long r = receivedMessages.get(); long p = producedMessages.get(); - LOG.info("published: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec, " + "consumed: " + r + " msgs at " + (r * 1000f / (end - start)) + " msgs/sec"); + LOG.info("published: {} msgs at {} msgs/sec, consumed: {} msgs at {} msgs/sec", p, p * 1000f / (end - start), r, r * 1000f / (end - start)); - StringBuffer fwdingmsg = new StringBuffer(500); + StringBuilder fwdingmsg = new StringBuilder(forwardingClients.length * 16); fwdingmsg.append(" forwarding counters: "); for (int j = 0; j < forwardingClients.length; j++) { if( j!= 0 ) { @@ -317,9 +317,9 @@ private String createMessageText(int index) { } LOG.info(fwdingmsg.toString()); - // The test is just checking to make sure thaat the producer and consumer does not hang + // The test is just checking to make sure that the producer and consumer does not hang // due to the network hops take to route the message form the producer to the consumer. - assertTrue("Recieved some messages since last sample", r>0); + assertTrue("Received some messages since last sample", r>0); assertTrue("Produced some messages since last sample", p>0); } @@ -332,5 +332,4 @@ private String createMessageText(int index) { } - } diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/test/JmsSendReceiveTestSupport.java b/activemq-unit-tests/src/test/java/org/apache/activemq/test/JmsSendReceiveTestSupport.java index 55f8b67f932..2800a37a97d 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/test/JmsSendReceiveTestSupport.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/test/JmsSendReceiveTestSupport.java @@ -77,7 +77,7 @@ protected void setUp() throws Exception { } } - LOG.info("Message count for test case is: " + messageCount); + LOG.info("Message count for test case is: {}", messageCount); data = new String[messageCount]; for (int i = 0; i < messageCount; i++) { data[i] = createMessageText(i); @@ -93,11 +93,7 @@ protected String createMessageText(int i) { } protected String createMessageBodyText() { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < largeMessageLoopSize; i++) { - buffer.append("0123456789"); - } - return buffer.toString(); + return "0123456789".repeat(Math.max(0, largeMessageLoopSize)); } /** @@ -111,7 +107,7 @@ public void testSendReceive() throws Exception { sendMessages(); assertMessagesAreReceived(); - LOG.info("" + data.length + " messages(s) received, closing down connections"); + LOG.info("{} messages(s) received, closing down connections", data.length); } protected void sendMessages() throws Exception { @@ -119,7 +115,7 @@ protected void sendMessages() throws Exception { Message message = createMessage(i); configureMessage(message); if (verbose) { - LOG.info("About to send a message: " + message + " with text: " + data[i]); + LOG.info("About to send a message: {} with text: {}", message, data[i]); } sendMessage(i, message); } @@ -130,8 +126,7 @@ protected void sendMessage(int index, Message message) throws Exception { } protected Message createMessage(int index) throws JMSException { - Message message = session.createTextMessage(data[index]); - return message; + return session.createTextMessage(data[index]); } /** @@ -166,7 +161,7 @@ protected void assertMessagesReceivedAreValid(List receivedMessages) th if (data.length != copyOfMessages.size()) { for (Iterator iter = copyOfMessages.iterator(); iter.hasNext();) { Object message = iter.next(); - LOG.info("<== " + counter++ + " = " + message); + LOG.info("<== {} = {}", counter++, message); } } @@ -191,7 +186,7 @@ protected void assertMessageValid(int index, Message message) throws JMSExceptio String text = textMessage.getText(); if (verbose) { - LOG.info("Received Text: " + text); + LOG.info("Received Text: {}", text); } assertEquals("Message: " + index, data[index], text); @@ -238,7 +233,7 @@ public synchronized void onMessage(Message message) { */ protected void consumeMessage(Message message, List messageList) { if (verbose) { - LOG.info("Received message: " + message); + LOG.info("Received message: {}", message); } messageList.add(message); diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOMaxFrameSizeCleanupTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOMaxFrameSizeCleanupTest.java index 81fe2869d00..5b838f5ce13 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOMaxFrameSizeCleanupTest.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOMaxFrameSizeCleanupTest.java @@ -120,7 +120,7 @@ protected void testMaxFrameSizeCleanup(String transportType, String clientUri) t } //Generate a body that is too large - StringBuffer body = new StringBuffer(); + StringBuilder body = new StringBuilder(); Random r = new Random(); for (int i = 0; i < 10000; i++) { body.append(r.nextInt()); diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java b/activemq-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java index aa80937797c..86bd37a358d 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java @@ -62,7 +62,7 @@ public void testSendingSmallMessage() throws Exception { expected.setPrefetchSize(3456); try { - LOG.info("About to send: " + expected); + LOG.info("About to send: {}", expected); producer.oneway(expected); Command received = assertCommandReceived(); @@ -72,7 +72,7 @@ public void testSendingSmallMessage() throws Exception { assertEquals("isExclusive", expected.isExclusive(), actual.isExclusive()); assertEquals("getPrefetchSize", expected.getPrefetchSize(), actual.getPrefetchSize()); } catch (Exception e) { - LOG.info("Caught: " + e); + LOG.info("Caught: {}", String.valueOf(e)); e.printStackTrace(); fail("Failed to send to transport: " + e); } @@ -99,7 +99,7 @@ protected void assertSendTextMessage(ActiveMQDestination destination, String tex expected.setDestination(destination); try { - LOG.info("About to send message of type: " + expected.getClass()); + LOG.info("About to send message of type: {}", expected.getClass()); producer.oneway(expected); // lets send a dummy command to ensure things don't block if we @@ -116,20 +116,16 @@ protected void assertSendTextMessage(ActiveMQDestination destination, String tex assertEquals("getDestination", expected.getDestination(), actual.getDestination()); assertEquals("getText", expected.getText(), actual.getText()); - LOG.info("Received text message with: " + actual.getText().length() + " character(s)"); + LOG.info("Received text message with: {} character(s)", actual.getText().length()); } catch (Exception e) { - LOG.info("Caught: " + e); + LOG.info("Caught: {}", String.valueOf(e)); e.printStackTrace(); fail("Failed to send to transport: " + e); } } protected String createMessageBodyText(int loopSize) { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < loopSize; i++) { - buffer.append("0123456789"); - } - return buffer.toString(); + return "0123456789".repeat(Math.max(0, loopSize)); } protected void setUp() throws Exception { @@ -162,11 +158,11 @@ public void onAcceptError(Exception error) { producer = createProducer(); producer.setTransportListener(new TransportListener() { public void onCommand(Object command) { - LOG.info("Producer received: " + command); + LOG.info("Producer received: {}", command); } public void onException(IOException error) { - LOG.info("Producer exception: " + error); + LOG.info("Producer exception: {}", String.valueOf(error)); error.printStackTrace(); } @@ -198,7 +194,7 @@ protected void tearDown() throws Exception { public void onCommand(Object o) { final Command command = (Command)o; if (command instanceof WireFormatInfo) { - LOG.info("Got WireFormatInfo: " + command); + LOG.info("Got WireFormatInfo: {}", command); } else { if (command.isResponseRequired()) { // lets send a response back... @@ -206,9 +202,9 @@ public void onCommand(Object o) { } if (large) { - LOG.info("### Received command: " + command.getClass() + " with id: " + command.getCommandId()); + LOG.info("### Received command: {} with id: {}", command.getClass(), command.getCommandId()); } else { - LOG.info("### Received command: " + command); + LOG.info("### Received command: {}", command); } synchronized (lock) { @@ -228,14 +224,14 @@ protected void sendResponse(Command command) { try { consumer.oneway(response); } catch (IOException e) { - LOG.info("Caught: " + e); + LOG.info("Caught: {}", String.valueOf(e)); e.printStackTrace(); throw new RuntimeException(e); } } public void onException(IOException error) { - LOG.info("### Received error: " + error); + LOG.info("### Received error: {}", String.valueOf(error)); error.printStackTrace(); } diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java index 16aeeb9209e..13d4e0e2b95 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java @@ -129,12 +129,12 @@ private void destroyBroker() throws Exception { protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { ObjectName objectName = new ObjectName(name); - LOG.info("** Looking for " + name); + LOG.info("** Looking for {}", name); try { if (mbeanServer.isRegistered(objectName)) { - LOG.info("Bean Registered: " + objectName); + LOG.info("Bean Registered: {}", objectName); } else { - LOG.info("Couldn't find Mbean! " + objectName); + LOG.info("Couldn't find Mbean! {}", objectName); } } catch (IOException e) { @@ -159,8 +159,8 @@ public void testPendingTopicStat() throws Exception { ObjectName subscriberObjName1 = set.iterator().next(); subscriber1 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, subscriberObjName1, DurableSubscriptionViewMBean.class, true); - LOG.info("Beginning Pending Queue Size count: " + subscriber1.getPendingQueueSize()); - LOG.info("Prefetch Limit: " + subscriber1.getPrefetchSize()); + LOG.info("Beginning Pending Queue Size count: {}", subscriber1.getPendingQueueSize()); + LOG.info("Prefetch Limit: {}", subscriber1.getPrefetchSize()); assertEquals("no pending", 0, subscriber1.getPendingQueueSize()); assertEquals("Prefetch Limit ", 10, subscriber1.getPrefetchSize()); @@ -191,10 +191,10 @@ public void testPendingTopicStat() throws Exception { producerSessions.commit(); } - LOG.info("Sent " + i + " messages in total"); + LOG.info("Sent {} messages in total", i); producerCon.close(); - LOG.info("Pending Queue Size count: " + subscriber1.getPendingQueueSize()); + LOG.info("Pending Queue Size count: {}", subscriber1.getPendingQueueSize()); assertEquals("pending as expected", 20, subscriber1.getPendingQueueSize()); LOG.info("Re-connect client and consume messages"); @@ -213,21 +213,21 @@ public boolean isSatisified() throws Exception { } })); - LOG.info("Received: " + listener.count); + LOG.info("Received: {}", listener.count); int pq = subscriber1.getPendingQueueSize(); - LOG.info("Pending Queue Size count: " + pq); + LOG.info("Pending Queue Size count: {}", pq); assertEquals("Pending queue after consumed", 0, pq); session2.close(); con2.close(); - LOG.info("FINAL Pending Queue Size count (after consumer close): " + subscriber1.getPendingQueueSize()); + LOG.info("FINAL Pending Queue Size count (after consumer close): {}", subscriber1.getPendingQueueSize()); } private String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(messageSize); - buffer.append("Message: " + index + " sent at: " + new Date()); + StringBuilder buffer = new StringBuilder(messageSize); + buffer.append("Message: ").append(index).append(" sent at: ").append(new Date()); if (buffer.length() > messageSize) { return buffer.substring(0, messageSize); } diff --git a/activemq-web-demo/src/test/java/org/apache/activemq/web/RestPersistentTest.java b/activemq-web-demo/src/test/java/org/apache/activemq/web/RestPersistentTest.java index 61345eaa80c..6bd2f79d1ce 100644 --- a/activemq-web-demo/src/test/java/org/apache/activemq/web/RestPersistentTest.java +++ b/activemq-web-demo/src/test/java/org/apache/activemq/web/RestPersistentTest.java @@ -77,7 +77,7 @@ public void postAndGet(String destinationType) throws Exception { private void postMessage(HttpClient httpClient, String url, String properties, String message) throws Exception { final CountDownLatch latch = new CountDownLatch(1); - final StringBuffer buf = new StringBuffer(); + final StringBuilder buf = new StringBuilder(); final AtomicInteger status = new AtomicInteger(); httpClient.newRequest(url+"&"+properties) .header("Content-Type","text/xml") @@ -99,7 +99,7 @@ private void getMessage(HttpClient httpClient, String url, String selector, Stri { final CountDownLatch latch = new CountDownLatch(1); - final StringBuffer buf = new StringBuffer(); + final StringBuilder buf = new StringBuilder(); final AtomicInteger status = new AtomicInteger(); Request request = httpClient.newRequest(url) .header("accept", "text/xml") diff --git a/activemq-web-demo/src/test/java/org/apache/activemq/web/RestTest.java b/activemq-web-demo/src/test/java/org/apache/activemq/web/RestTest.java index 7617ddb8b68..a47dd73a951 100644 --- a/activemq-web-demo/src/test/java/org/apache/activemq/web/RestTest.java +++ b/activemq-web-demo/src/test/java/org/apache/activemq/web/RestTest.java @@ -180,7 +180,7 @@ public void testCorrelation() throws Exception { asyncRequest(httpClient, "http://localhost:" + port + "/message/test?readTimeout=1000&type=queue&clientId=test", buf); assertEquals(HttpStatus.OK_200, result.get().getResponse().getStatus()); - LOG.info("Received: " + buf); + LOG.info("Received: {}", buf); assertEquals(correlId, buf.toString()); } httpClient.stop(); @@ -199,9 +199,9 @@ public void testDisconnect() throws Exception { asyncRequest(httpClient, "http://localhost:" + port + "/message/test?readTimeout=1000&type=queue&clientId=test", buf); assertEquals(HttpStatus.OK_200, result.get().getResponse().getStatus()); - LOG.info("Received: " + buf); + LOG.info("Received: {}", buf); - final StringBuffer buf2 = new StringBuffer(); + final StringBuilder buf2 = new StringBuilder(); final CountDownLatch latch2 = new CountDownLatch(1); httpClient.newRequest("http://localhost:" + port + "/message/test?clientId=test&action=unsubscribe") .method(HttpMethod.POST).send(new BufferingResponseListener() { diff --git a/assembly/src/test/java/org/apache/activemq/benchmark/Producer.java b/assembly/src/test/java/org/apache/activemq/benchmark/Producer.java index 5ece08a67c3..cc8ab794c16 100644 --- a/assembly/src/test/java/org/apache/activemq/benchmark/Producer.java +++ b/assembly/src/test/java/org/apache/activemq/benchmark/Producer.java @@ -118,7 +118,7 @@ public void run() { } protected String getMessage() { - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(messageSize); for (int i = 0; i < messageSize; i++) { char ch = 'X'; buffer.append(ch); @@ -164,7 +164,7 @@ protected void publishLoop(Session session, MessageProducer publisher, String te protected String loadFile(String file) throws IOException { System.out.println("Loading file: " + file); - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); BufferedReader in = new BufferedReader(new FileReader(file)); while (true) { String line = in.readLine();