Skip to content

Stringbuffer cleanup part2 (splitted commits) #1471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 29 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
45be7ef
use StringBuilder instead of StringBuffer in join method
Jul 8, 2025
d22f719
rewrite some logging to use params instead of concatenation
Jul 8, 2025
3220a40
use StringBuilder instead of StringBuffer in validate method
Jul 8, 2025
77b5bf5
use StringBuilder instead of StringBuffer
Jul 8, 2025
2a38eeb
rewrite some logging to use params instead of concatenation
Jul 8, 2025
9b2864e
rewrite some logging to use params instead of concatenation
Jul 8, 2025
86c7e4e
use StringBuilder instead of StringBuffer
Jul 8, 2025
af7caaf
use StringBuilder instead of StringBuffer
Jul 8, 2025
1a6e280
use StringBuilder instead of StringBuffer
Jul 8, 2025
a1390ae
use StringBuilder instead of StringBuffer
Jul 8, 2025
167c8aa
use StringBuilder instead of StringBuffer
Jul 8, 2025
dde36ea
use StringBuilder instead of StringBuffer
Jul 8, 2025
9712e8a
avoid StringBuffer and use java 11 String#repeat
Jul 8, 2025
21b4672
use StringBuilder instead of StringBuffer
Jul 8, 2025
af147ac
use StringBuilder instead of StringBuffer in join method
Jul 8, 2025
89e2769
rewrite some logging to use params instead of concatenation
Jul 8, 2025
a052e40
use StringBuilder instead of StringBuffer in validate method
Jul 8, 2025
234113a
use StringBuilder instead of StringBuffer
Jul 8, 2025
3440022
rewrite some logging to use params instead of concatenation
Jul 8, 2025
d29677c
rewrite some logging to use params instead of concatenation
Jul 8, 2025
e968807
use StringBuilder instead of StringBuffer
Jul 8, 2025
acc4bd3
use StringBuilder instead of StringBuffer
Jul 8, 2025
67c34db
use StringBuilder instead of StringBuffer
Jul 8, 2025
b3e0b09
use StringBuilder instead of StringBuffer
Jul 8, 2025
677dd18
use StringBuilder instead of StringBuffer
Jul 8, 2025
856d802
use StringBuilder instead of StringBuffer
Jul 8, 2025
1342038
avoid StringBuffer and use java 11 String#repeat
Jul 8, 2025
37d61b8
use StringBuilder instead of StringBuffer
Jul 8, 2025
7c42719
Merge remote-tracking branch 'origin/feature/cleanup_part2_stringbuff…
Jul 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,22 @@
*/
package org.apache.activemq.transport.amqp.client.sasl;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.security.sasl.SaslException;

import static java.nio.charset.StandardCharsets.US_ASCII;

/**
* Implements the SASL PLAIN authentication Mechanism.
*
* User name and Password values are sent without being encrypted.
*/
public class CramMD5Mechanism extends AbstractMechanism {

private static final String ASCII = "ASCII";
private static final String HMACMD5 = "HMACMD5";
private boolean sentResponse;

Expand All @@ -54,26 +54,25 @@ 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');
}
hash.append(hex);
}

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) {
Expand All @@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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<String, ? extends Object> options) throws URISyntaxException {
try {
if (options.size() > 0) {
StringBuffer rc = new StringBuffer();
boolean first = true;
for (Entry<String, ? extends Object> 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<String, ? extends Object> options) {
if (!options.isEmpty()) {
StringBuilder rc = new StringBuilder();
boolean first = true;
for (Entry<String, ? extends Object> 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 "";
}
}

Expand Down Expand Up @@ -196,8 +192,8 @@ public static Map<String, String> 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(" ");
}
Expand Down Expand Up @@ -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()));
Expand Down Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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 \"$@\"";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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<KahaDestination, opCount> op : destinationOpCount.entrySet()) {
buffer.append(op.getKey()).append('+').append(op.getValue().add).append(',').append('-').append(op.getValue().remove).append(';');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> 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()]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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.");
Expand Down
Loading