Skip to content

Commit

Permalink
Tidy for older Java language features
Browse files Browse the repository at this point in the history
  • Loading branch information
chadlwilson committed Jan 14, 2024
1 parent 763baaf commit 1f3fee0
Show file tree
Hide file tree
Showing 21 changed files with 62 additions and 85 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ private String property(final String name, String value) {
private String javaCmd() {
String javaHome = System.getProperty("java.home");
String pathSep = System.getProperty("file.separator");
return javaHome + pathSep + "bin" + pathSep + "java";
return String.join(pathSep, javaHome, "bin", "java");
}

Process invoke(String[] command) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.List;
import java.util.Properties;

import static java.nio.charset.StandardCharsets.UTF_8;
Expand Down Expand Up @@ -147,7 +148,7 @@ public void writeProperty(String key, Object value, boolean forceSingleLine) thr
scrubWithMessage("The autoregister key has been intentionally removed by Go as a security measure.");
}

if (key.equals(AGENT_AUTO_REGISTER_RESOURCES) || key.equals(AGENT_AUTO_REGISTER_ENVIRONMENTS) || key.equals(AGENT_AUTO_REGISTER_HOSTNAME)) {
if (List.of(AGENT_AUTO_REGISTER_RESOURCES, AGENT_AUTO_REGISTER_ENVIRONMENTS, AGENT_AUTO_REGISTER_HOSTNAME).contains(key)) {
scrubWithMessage("This property has been removed by Go after attempting to auto-register with the Go server.");
}
super.writeProperty(key, value, forceSingleLine);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ void testToStringWithSeparator() {
assertEquals(ARG_SPACES_NOQUOTES + separator + ARG_NOSPACES,
CommandLine.toString(new String[]{ARG_SPACES_NOQUOTES, ARG_NOSPACES}, false, separator));

assertEquals(ARG_SPACES_NOQUOTES + separator + ARG_NOSPACES + separator + ARG_SPACES,
assertEquals(String.join(separator, ARG_SPACES_NOQUOTES, ARG_NOSPACES, ARG_SPACES),
CommandLine.toString(new String[]{ARG_SPACES_NOQUOTES, ARG_NOSPACES, ARG_SPACES},
false, separator));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public static HealthStateScope forStage(String pipelineName, String stageName) {
}

public static HealthStateScope forJob(String pipelineName, String stageName, String jobName) {
return new HealthStateScope(ScopeType.JOB, pipelineName + "/" + stageName + "/" + jobName);
return new HealthStateScope(ScopeType.JOB, String.join("/", pipelineName, stageName, jobName));
}

public static HealthStateScope forMaterial(Material material) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,7 @@ private ActualTransactionTemplate(TestTransactionSynchronizationManager synchron
o = action.doInTransaction(null);
synchronizationManager.executeAfterCompletion(TransactionSynchronization.STATUS_COMMITTED);
synchronizationManager.executeAfterCommit();
} catch (RuntimeException e) {
synchronizationManager.executeAfterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
throw e;
} catch (Error e) {
} catch (RuntimeException | Error e) {
synchronizationManager.executeAfterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
throw e;
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.stream.Stream;

public class DigestObjectPools {

Expand All @@ -41,7 +42,7 @@ public DigestObjectPools(CreateDigest createDigest) {
}

public String computeDigest(String algorithm, DigestOperation operation) {
if (!SHA_512_256.equals(algorithm) && !SHA_256.equals(algorithm) && !MD5.equals(algorithm)) {
if (Stream.of(SHA_512_256, SHA_256, MD5).noneMatch(s -> s.equals(algorithm))) {
throw new IllegalArgumentException("Algorithm not supported");
}
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,6 @@ public void shouldEscapeDynamicLink() {
}

private String dynamicLink(String id) {
return "<a href=\"http://mingle05/projects/cce/cards/" + id + "\" target=\"story_tracker\">#" + id + "</a>";
return String.join(id, "<a href=\"http://mingle05/projects/cce/cards/", "\" target=\"story_tracker\">#", "</a>");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public void validateUsing(Validator<String> validator) throws ValidationExceptio

public boolean matches(String comment) {
for (String escapedMatcher : escapeMatchers()) {
Pattern pattern = Pattern.compile("\\B" + escapedMatcher + "\\B|\\b" + escapedMatcher + "\\b");
Pattern pattern = Pattern.compile(String.join(escapedMatcher, "\\B", "\\B|\\b", "\\b"));
if (pattern.matcher(comment).find()) {
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.thoughtworks.go.domain.JobState;

import java.util.Date;
import java.util.stream.Stream;

public class JobHistoryItem implements BuildStateAware {
private long id;
Expand Down Expand Up @@ -94,6 +95,6 @@ public boolean hasFailed() {
}

public boolean isRunning() {
return state == JobState.Assigned || state == JobState.Preparing || state == JobState.Building || state == JobState.Completing || state == JobState.Scheduled;
return Stream.of(JobState.Assigned, JobState.Preparing, JobState.Building, JobState.Completing, JobState.Scheduled).anyMatch(jobState -> state == jobState);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

Expand All @@ -64,10 +65,7 @@ public PluginsZip(SystemEnvironment systemEnvironment, PluginManager pluginManag
externalPlugins = new File(systemEnvironment.get(SystemEnvironment.PLUGIN_EXTERNAL_PROVIDED_PATH));
this.pluginManager = pluginManager;
this.pluginManager.addPluginChangeListener(this);
predicate = goPluginDescriptor -> PluginsZip.this.pluginManager.isPluginOfType("task", goPluginDescriptor.id()) ||
PluginsZip.this.pluginManager.isPluginOfType("scm", goPluginDescriptor.id()) ||
PluginsZip.this.pluginManager.isPluginOfType("package-repository", goPluginDescriptor.id()) ||
PluginsZip.this.pluginManager.isPluginOfType("artifact", goPluginDescriptor.id());
predicate = goPluginDescriptor -> Stream.of("task", "scm", "package-repository", "artifact").anyMatch(s -> PluginsZip.this.pluginManager.isPluginOfType(s, goPluginDescriptor.id()));
}

public void create() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,7 @@ protected Map<String, String> generateOSGiFrameworkConfig() {

Map<String, String> config = new HashMap<>();
config.put(Constants.FRAMEWORK_BUNDLE_PARENT, Constants.FRAMEWORK_BUNDLE_PARENT_FRAMEWORK);
config.put(Constants.FRAMEWORK_BOOTDELEGATION, osgiFrameworkPackage + ", " + goPluginApiPackage + ", " + subPackagesOfGoPluginApiPackage
+ ", " + internalServicesPackage + ", " + javaxPackages + ", " + orgXmlSaxPackages + ", " + orgW3cDomPackages);
config.put(Constants.FRAMEWORK_BOOTDELEGATION, String.join(", ", osgiFrameworkPackage, goPluginApiPackage, subPackagesOfGoPluginApiPackage, internalServicesPackage, javaxPackages, orgXmlSaxPackages, orgW3cDomPackages));
config.put(Constants.FRAMEWORK_STORAGE_CLEAN, "onFirstInit");
config.put(BundleCache.CACHE_LOCKING_PROP, "false");
config.put(FelixConstants.SERVICE_URLHANDLERS_PROP, "false");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public void error(String pluginId, String loggerName, String message, Object...

private Logger getLogger(String pluginId, String loggerName) {
initializeLoggerForPluginId(pluginId);
return LoggerFactory.getLogger(PLUGIN_LOGGER_PREFIX + "." + pluginId + "." + loggerName);
return LoggerFactory.getLogger(String.join(".", PLUGIN_LOGGER_PREFIX, pluginId, loggerName));
}

private boolean alreadyInitialized(String pluginId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,20 +185,17 @@ void shouldAllowSettingLoggingLevelPerPlugin() throws IOException {
}

private Thread createThreadFor(final String pluginId, final String threadIdentifier) {
return new Thread() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
pluginLoggingService.info(pluginId, "LoggingClass", "info-" + threadIdentifier + "-" + i);

try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return new Thread(() -> {
for (int i = 0; i < 100; i++) {
pluginLoggingService.info(pluginId, "LoggingClass", "info-" + threadIdentifier + "-" + i);

try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
});
}

private void assertMessageInLog(File pluginLogFile, String expectedLoggingLevel, String loggerName, String expectedLogMessage) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;

import static com.thoughtworks.go.util.GoConstants.ERROR_FOR_JSON;
import static com.thoughtworks.go.util.GoConstants.RESPONSE_CHARSET_JSON;
Expand Down Expand Up @@ -79,10 +80,7 @@ public static JsonAction jsonConflict(Object json) {
}

public static JsonAction jsonByValidity(Object json, GoConfigValidity.InvalidGoConfig configValidity) {
return (configValidity.isType(GoConfigValidity.VT_CONFLICT) ||
configValidity.isType(GoConfigValidity.VT_MERGE_OPERATION_ERROR) ||
configValidity.isType(GoConfigValidity.VT_MERGE_POST_VALIDATION_ERROR) ||
configValidity.isType(GoConfigValidity.VT_MERGE_PRE_VALIDATION_ERROR)) ? jsonConflict(json) : jsonNotFound(json);
return (Stream.of(GoConfigValidity.VT_CONFLICT, GoConfigValidity.VT_MERGE_OPERATION_ERROR, GoConfigValidity.VT_MERGE_POST_VALIDATION_ERROR, GoConfigValidity.VT_MERGE_PRE_VALIDATION_ERROR).anyMatch(configValidity::isType)) ? jsonConflict(json) : jsonNotFound(json);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public void pause(String pipelineName, String pauseCause, Username pausedBy, Loc
pauseCause = "";
}
if (isPipelinePaused(pipelineName)) {
result.conflict("Failed to pause pipeline '" +pipelineName + "'. Pipeline '" +pipelineName + "' is already paused.");
result.conflict(String.join(pipelineName, "Failed to pause pipeline '", "'. Pipeline '", "' is already paused."));
return;
}
try {
Expand All @@ -96,7 +96,7 @@ public void unpause(String pipelineName, Username unpausedBy, LocalizedOperation
return;
}
if (!isPipelinePaused(pipelineName)) {
result.conflict("Failed to unpause pipeline '" + pipelineName + "'. Pipeline '" + pipelineName + "' is already unpaused.");
result.conflict(String.join(pipelineName, "Failed to unpause pipeline '", "'. Pipeline '", "' is already unpaused."));
return;
}
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,6 @@ public void shouldFetchFolder() throws Exception {
buildWork.doWork(environmentVariableContext, new AgentWorkContext(agentIdentifier, buildRepository, stubManipulator,
new AgentRuntimeInfo(agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie"), null, null, null, null, null));

assertThat(stubManipulator.artifact().get(0), is(new DirHandler("lib", new File("pipelines" + File.separator + PIPELINE_NAME + File.separator + DEST))));
assertThat(stubManipulator.artifact().get(0), is(new DirHandler("lib", new File(String.join(File.separator, "pipelines", PIPELINE_NAME, DEST)))));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,24 +123,21 @@ public void shouldProcessAllActionsInOrderOfThemBeingAdded() throws Exception {
}

private Thread setupNewThreadToAddActionIn(final ThreadNameAccumulator threadNameAccumulator) {
return new Thread() {
@Override
public void run() {
threadNameAccumulator.threadOfQueueAdd = Thread.currentThread().getName();

queueProcessor.add(new Action() {
@Override
public void call() {
threadNameAccumulator.threadOfCall = Thread.currentThread().getName();
}

@Override
public String description() {
return "some-action";
}
});
}
};
return new Thread(() -> {
threadNameAccumulator.threadOfQueueAdd = Thread.currentThread().getName();

queueProcessor.add(new Action() {
@Override
public void call() {
threadNameAccumulator.threadOfCall = Thread.currentThread().getName();
}

@Override
public String description() {
return "some-action";
}
});
});
}

private void waitForProcessingToHappen() throws InterruptedException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ void shouldWarnIfFailedToSaveFileWhenAttemptIsBelowMaxAttempts() throws IOExcept
final ByteArrayInputStream stream = new ByteArrayInputStream("".getBytes());
String buildInstanceId = "1";
final File destFile = new File(logsDir,
buildInstanceId + File.separator + "generated" + File.separator + LOG_XML_NAME);
String.join(File.separator, buildInstanceId, "generated", LOG_XML_NAME));
final IOException ioException = new IOException();

assumeArtifactsRoot(logsDir);
Expand All @@ -138,7 +138,7 @@ void shouldLogErrorIfFailedToSaveFileWhenAttemptHitsMaxAttempts() throws IOExcep
final ByteArrayInputStream stream = new ByteArrayInputStream("".getBytes());
String buildInstanceId = "1";
final File destFile = new File(logsDir,
buildInstanceId + File.separator + "generated" + File.separator + LOG_XML_NAME);
String.join(File.separator, buildInstanceId, "generated", LOG_XML_NAME));
final IOException ioException = new IOException();

doThrow(ioException).when(zipUtil).unzip(any(ZipInputStream.class), any(File.class));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,27 +98,21 @@ public void shouldNotThrowUpWhenSameMaterialIsBeingUpdatedByMultipleThreads() th
final List<Exception> threadOneExceptions = new ArrayList();
final List<Exception> threadTwoExceptions = new ArrayList();

Thread updateThread1 = new Thread() {
@Override
public void run() {
try {
updater.updateMaterial(material);
} catch (Exception e) {
threadOneExceptions.add(e);
}
Thread updateThread1 = new Thread(() -> {
try {
updater.updateMaterial(material);
} catch (Exception e) {
threadOneExceptions.add(e);
}
};

Thread updateThread2 = new Thread() {
@Override
public void run() {
try {
updater.updateMaterial(material);
} catch (Exception e) {
threadTwoExceptions.add(e);
}
});

Thread updateThread2 = new Thread(() -> {
try {
updater.updateMaterial(material);
} catch (Exception e) {
threadTwoExceptions.add(e);
}
};
});

updateThread1.start();
updateThread2.start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.util.Iterator;
import java.util.List;
import java.util.UUID;

Expand Down Expand Up @@ -214,9 +213,7 @@ public void ensureDashboardReturnsJustOneInstanceOfPipelineAddedViaAPiConsistent
private void assertThereIsExactlyOneInstanceOfEachPipelineOnDashboard(List<GoDashboardPipelineGroup> dashboardAfterPipelineCreationViaApi) {
assertThat(dashboardAfterPipelineCreationViaApi, hasSize(1));//pipeline group
assertThat(dashboardAfterPipelineCreationViaApi.get(0).allPipelines(), hasSize(goConfigService.cruiseConfig().getAllPipelineNames().size()));
Iterator<GoDashboardPipeline> iterator = dashboardAfterPipelineCreationViaApi.get(0).allPipelines().iterator();
while (iterator.hasNext()){
GoDashboardPipeline dashboardPipeline = iterator.next();
for (GoDashboardPipeline dashboardPipeline : dashboardAfterPipelineCreationViaApi.get(0).allPipelines()) {
assertThat(dashboardPipeline.model().getName(), dashboardPipeline.model().getActivePipelineInstances(), hasSize(1));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package com.thoughtworks.go.util.command;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

Expand All @@ -38,9 +37,7 @@ public CompositeConsumer(StreamConsumer... consumers) {

@Override
public void taggedConsumeLine(String tag, String line) {
Iterator i = consumers.iterator();
while (i.hasNext()) {
StreamConsumer consumer = (StreamConsumer) i.next();
for (StreamConsumer consumer : consumers) {
if (null != tag && consumer instanceof TaggedStreamConsumer) {
((TaggedStreamConsumer) consumer).taggedConsumeLine(tag, line);
} else {
Expand Down

0 comments on commit 1f3fee0

Please sign in to comment.