Skip to content

Commit

Permalink
String handling clean-ups
Browse files Browse the repository at this point in the history
* Remove unnecessary empty string for blank lines.
* Use the indexed variant of StringBuilder.append() to avoid extra
  calls to substring().
* Remove unnecessary length() calls when extracting a substring to the
  end of the string.
* Avoid concatenating strings inside StringBuilder.append() calls.
* Avoid concatenating strings in loops.
* Avoid explicit StringBuilders when concatenation suffices (with no
  performance impact).
* Remove unnecessary explicit .toString() calls.

Signed-off-by: Stephen Kitt <[email protected]>
  • Loading branch information
skitt committed May 21, 2019
1 parent c827346 commit 8833b6e
Show file tree
Hide file tree
Showing 44 changed files with 238 additions and 261 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ private void rotate(Path path, long timestamp) {
String name = fix[0] + "-" + date + fix[1];
int idx = 0;
while (sameDate.contains(name)) {
name = fix[0] + "-" + date + "-" + Integer.toString(++idx) + fix[1];
name = fix[0] + "-" + date + "-" + (++idx) + fix[1];
}
paths.add(name);
Path finalPath = path.resolveSibling(name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ protected Object doExecute(List<Bundle> bundles) throws Exception {
{
if (separatorNeeded)
{
System.out.println("");
System.out.println();
}

// Print out any matching generic capabilities.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ protected void executeOnBundle(Bundle bundle) throws Exception {
stringBuilder.append(SimpleAnsi.INTENSITY_BOLD);
}
if(ids == null || ids.size() != 1) {
stringBuilder.append(bundle.getBundleId() + " | ");
stringBuilder.append(bundle.getBundleId()).append(" | ");
}
stringBuilder.append(resource + " | ");
stringBuilder.append("exported: " + isExported(resource, exports));
stringBuilder.append(resource).append(" | ");
stringBuilder.append("exported: ").append(isExported(resource, exports));
if(localResource) {
stringBuilder.append(SimpleAnsi.INTENSITY_NORMAL);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,10 @@ private String printHosts(BundleInfo info) {
builder.append(", Hosts: ");
boolean first = true;
for (Bundle host : info.getFragmentHosts()) {
builder.append((first ? "" : ", ") + host.getBundleId());
if (!first) {
builder.append(", ");
}
builder.append(host.getBundleId());
first = false;
}
return builder.toString();
Expand All @@ -199,7 +202,10 @@ private String printFragments(BundleInfo info) {
builder.append(", Fragments: ");
boolean first = true;
for (Bundle host : info.getFragments()) {
builder.append((first ? "" : ", ") + host.getBundleId());
if (!first) {
builder.append(", ");
}
builder.append(host.getBundleId());
first = false;
}
return builder.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ protected Object doExecute(List<Bundle> bundles) throws Exception {
Pattern ns = Pattern.compile(namespace.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*"));
for (Bundle b : bundles) {
if (separatorNeeded) {
System.out.println("");
System.out.println();
}

// Print out any matching generic requirements.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ private void printServices(Bundle bundle, ServiceReference<?>[] refs, boolean sh
// Print header if we have not already done so.
if (!headerPrinted) {
headerPrinted = true;
System.out.println("");
System.out.println();
String title = ShellUtil.getBundleName(bundle) + ((inUse) ? " uses:" : " provides:");
System.out.println(title);
System.out.println(ShellUtil.getUnderlineString(title));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,15 @@ private void populateFragementInfos(Bundle bundle) {
}

private String populateRevisions(Bundle bundle) {
String ret = "";
BundleRevisions revisions = bundle.adapt(BundleRevisions.class);
if (revisions == null) {
return ret;
return "";
}
StringBuilder ret = new StringBuilder();
for (BundleRevision revision : revisions.getRevisions()) {
ret = ret + "[" + revision + "]" + " ";
ret.append("[").append(revision).append("]").append(" ");
}
return ret;
return ret.toString();
}

private void getFragments(BundleRevision revision) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,15 @@ protected void writeDump(OutputStreamWriter outputStream) throws Exception {
}

protected String getDumpThreadString(ThreadInfo threadInfo) {
StringBuilder sb = new StringBuilder("\"" + threadInfo.getThreadName() + "\"" + " Id=" + threadInfo.getThreadId() + " "
+ threadInfo.getThreadState());
StringBuilder sb = new StringBuilder();
sb.append("\"").append(threadInfo.getThreadName()).append("\"").append(" Id=").append(
threadInfo.getThreadId()).append(" ").append(threadInfo.getThreadState());
if (threadInfo.getLockName() != null) {
sb.append(" on " + threadInfo.getLockName());
sb.append(" on ").append(threadInfo.getLockName());
}
if (threadInfo.getLockOwnerName() != null) {
sb.append(" owned by \"" + threadInfo.getLockOwnerName() + "\" Id=" + threadInfo.getLockOwnerId());
sb.append(" owned by \"").append(threadInfo.getLockOwnerName()).append("\" Id=").append(
threadInfo.getLockOwnerId());
}
if (threadInfo.isSuspended()) {
sb.append(" (suspended)");
Expand All @@ -68,21 +70,21 @@ protected String getDumpThreadString(ThreadInfo threadInfo) {
StackTraceElement[] stackTrace = threadInfo.getStackTrace();
for (; i < stackTrace.length; i++) {
StackTraceElement ste = stackTrace[i];
sb.append("\tat " + ste.toString());
sb.append("\tat ").append(ste.toString());
sb.append('\n');
if (i == 0 && threadInfo.getLockInfo() != null) {
Thread.State ts = threadInfo.getThreadState();
switch (ts) {
case BLOCKED:
sb.append("\t- blocked on " + threadInfo.getLockInfo());
sb.append("\t- blocked on ").append(threadInfo.getLockInfo());
sb.append('\n');
break;
case WAITING:
sb.append("\t- waiting on " + threadInfo.getLockInfo());
sb.append("\t- waiting on ").append(threadInfo.getLockInfo());
sb.append('\n');
break;
case TIMED_WAITING:
sb.append("\t- waiting on " + threadInfo.getLockInfo());
sb.append("\t- waiting on ").append(threadInfo.getLockInfo());
sb.append('\n');
break;
default:
Expand All @@ -91,7 +93,7 @@ protected String getDumpThreadString(ThreadInfo threadInfo) {

for (MonitorInfo mi : threadInfo.getLockedMonitors()) {
if (mi.getLockedStackDepth() == i) {
sb.append("\t- locked " + mi);
sb.append("\t- locked ").append(mi);
sb.append('\n');
}
}
Expand All @@ -103,10 +105,10 @@ protected String getDumpThreadString(ThreadInfo threadInfo) {

LockInfo[] locks = threadInfo.getLockedSynchronizers();
if (locks.length > 0) {
sb.append("\n\tNumber of locked synchronizers = " + locks.length);
sb.append("\n\tNumber of locked synchronizers = ").append(locks.length);
sb.append('\n');
for (LockInfo li : locks) {
sb.append("\t- " + li);
sb.append("\t- ").append(li);
sb.append('\n');
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ static Map<String, String> parse(List<String> propList) {
throw new IllegalArgumentException("Invalid property " + keyValue);
} else {
String key = keyValue.substring(0, splitAt);
String value = keyValue.substring(splitAt + 1, keyValue.length());
String value = keyValue.substring(splitAt + 1);
properties.put(key, value);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ private void displayBundleInformation(Feature feature, String contentType) {
sb.append(" start-level=").append(startLevel);
}
if (featureBundle.isOverriden() != BundleInfo.BundleOverrideMode.NONE) {
sb.append(" (overriden from " + featureBundle.getOriginalLocation() + ")");
sb.append(" (overriden from ").append(featureBundle.getOriginalLocation()).append(")");
}
System.out.println(sb.toString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public static org.apache.karaf.features.Feature valueOf(String str) {
int idx = str.indexOf(VERSION_SEPARATOR);
if (idx >= 0) {
String strName = str.substring(0, idx);
String strVersion = str.substring(idx + 1, str.length());
String strVersion = str.substring(idx + 1);
return new Feature(strName, strVersion);
} else {
return new Feature(str);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,11 @@ public List<ServletInfo> getServlets() {
String servletClassName = " ";
if (servlet != null) {
servletClassName = servlet.getClass().getName();
servletClassName = servletClassName.substring(servletClassName.lastIndexOf(".") + 1,
servletClassName.length());
servletClassName = servletClassName.substring(servletClassName.lastIndexOf(".") + 1);
}
String servletName = event.getServletName() != null ? event.getServletName() : " ";
if (servletName.contains(".")) {
servletName = servletName.substring(servletName.lastIndexOf(".") + 1, servletName.length());
servletName = servletName.substring(servletName.lastIndexOf(".") + 1);
}

String alias = event.getAlias();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,33 +108,24 @@ void encryptedPassword(Properties users) throws IOException {
boolean changed = false;
for (String userName : users.keySet()) {
String user = userName;
String userInfos = users.get(user);

if (user.startsWith(PropertiesBackingEngine.GROUP_PREFIX)) {
continue;
}

// the password is in the first position
String[] infos = userInfos.split(",");
String[] infos = users.get(user).split(",");
String storedPassword = infos[0];

// check if the stored password is flagged as encrypted
String encryptedPassword = encryptionSupport.encrypt(storedPassword);
if (!storedPassword.equals(encryptedPassword)) {
LOGGER.debug("The password isn't flagged as encrypted, encrypt it.");
userInfos = encryptedPassword + ",";
for (int i = 1; i < infos.length; i++) {
if (i == (infos.length - 1)) {
userInfos = userInfos + infos[i];
} else {
userInfos = userInfos + infos[i] + ",";
}
}
if (user.contains("\\")) {
users.remove(user);
user = user.replace("\\", "\\\\");
}
users.put(user, userInfos);
users.put(user, encryptedPassword + "," + String.join(",", infos));
changed = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,23 +373,23 @@ void handleInvoke(BulkRequestContext context, ObjectName objectName, String oper

private void printDetailedMessage(BulkRequestContext context, ObjectName objectName,
String operationName, Object[] params, String[] signature) throws IOException {
String expectedRoles = "";
StringBuilder expectedRoles = new StringBuilder();
for (String role : getRequiredRoles(context, objectName, operationName, params, signature)) {
if (expectedRoles.length() != 0) {
expectedRoles = expectedRoles + ", " + role;
expectedRoles.append(", ").append(role);
} else {
expectedRoles = role;
expectedRoles = new StringBuilder(role);
}
}
String currentRoles = "";
StringBuilder currentRoles = new StringBuilder();
for (Principal p : context.getPrincipals()) {
if (!p.getClass().getName().endsWith("RolePrincipal")) {
continue;
}
if (currentRoles.length() != 0) {
currentRoles = currentRoles + ", " + p.getName();
currentRoles.append(", ").append(p.getName());
} else {
currentRoles = p.getName();
currentRoles = new StringBuilder(p.getName());
}
}
String matchedPid = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -391,11 +391,9 @@ public boolean isFileRepository()
@Override
public String toString()
{
return new StringBuilder()
.append( m_repositoryURL.toString() )
.append( ",releases=" ).append( m_releasesEnabled )
.append( ",snapshots=" ).append( m_snapshotsEnabled )
.toString();
return m_repositoryURL.toString()
+ ",releases=" + m_releasesEnabled
+ ",snapshots=" + m_snapshotsEnabled;
}

public String asRepositorySpec() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ protected void doExecute(RepositoryAdmin admin) throws Exception {
{
if (resIdx > 0)
{
System.out.println("");
System.out.println();
}
printResource(System.out, resources[resIdx]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ protected void doExecute(RepositoryAdmin admin) throws Exception {
{
if (resIdx > 0)
{
System.out.println("");
System.out.println();
}
printResource(System.out, resources[resIdx]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ protected void printUnderline(PrintStream out, int length) {
for (int i = 0; i < length; i++) {
out.print('-');
}
out.println("");
out.println();
}

protected void doDeploy(RepositoryAdmin admin, List<String> bundles, boolean start, boolean deployOptional) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ private void checkDuplicateExports() {
private String getBundlesSt(Set<Bundle> bundles) {
StringBuilder st = new StringBuilder();
for (Bundle bundle : bundles) {
st.append(bundle.getBundleId() + " ");
st.append(bundle.getBundleId()).append(" ");
}
return st.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public static String bind(String message, Object[] bindings) {
break;
}
// otherwise write out the chars inside the quotes
buffer.append(message.substring(nextIndex, index));
buffer.append(message, nextIndex, index);
i = index;
break;
default :
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ private void printThread(String indent) {
StringBuilder sb = new StringBuilder("\"" + info.getThreadName() + "\"" + " Id="
+ info.getThreadId() + " in " + info.getThreadState());
if (info.getLockName() != null) {
sb.append(" on lock=" + info.getLockName());
sb.append(" on lock=").append(info.getLockName());
}
if (info.isSuspended()) {
sb.append(" (suspended)");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -436,9 +436,9 @@ protected void printUsage(CommandSession session, Action action, Map<Option, Fie
if (options.size() > 0) {
out.println(INTENSITY_BOLD + "OPTIONS" + INTENSITY_NORMAL);
for (Option option : options) {
String opt = option.name();
StringBuilder opt = new StringBuilder(option.name());
for (String alias : option.aliases()) {
opt += ", " + alias;
opt.append(", ").append(alias);
}
out.print(" ");
out.println(INTENSITY_BOLD + opt + INTENSITY_NORMAL);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,9 @@ public void printUsage(Action action, PrintStream out, boolean globalScope, int
if (options.size() > 0) {
out.println(INTENSITY_BOLD + "OPTIONS" + INTENSITY_NORMAL);
for (Option option : optionsSet) {
String opt = option.name();
StringBuilder opt = new StringBuilder(option.name());
for (String alias : option.aliases()) {
opt += ", " + alias;
opt.append(", ").append(alias);
}
out.print(" ");
out.println(INTENSITY_BOLD + opt + INTENSITY_NORMAL);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,8 @@ private String convertArgs(String commandACLArgs) {
if (!commandACLArgs.endsWith("/]")) {
throw new IllegalStateException("Badly formatted argument match: " + commandACLArgs + " Should end with '/]'");
}
StringBuilder sb = new StringBuilder();
sb.append("[/.*/,"); // add a wildcard argument since the Function execute method has the arguments as second arg
sb.append(commandACLArgs.substring(1));
return sb.toString();
return "[/.*/," // add a wildcard argument since the Function execute method has the arguments as second arg
+ commandACLArgs.substring(1);
}

void deleteServiceGuardConfig(String originatingPid, String scope) throws IOException, InvalidSyntaxException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ public static String getBundleName(Bundle bundle) {
if (bundle != null) {
String name = bundle.getHeaders().get(Constants.BUNDLE_NAME);
return (name == null)
? "Bundle " + Long.toString(bundle.getBundleId())
: name + " (" + Long.toString(bundle.getBundleId()) + ")";
? "Bundle " + bundle.getBundleId()
: name + " (" + bundle.getBundleId() + ")";
}
return "[STALE BUNDLE]";
}
Expand Down
Loading

0 comments on commit 8833b6e

Please sign in to comment.