Skip to content
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

Clean-up code base to improve code quality #2195

Merged
merged 6 commits into from
Feb 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 1 addition & 2 deletions cli/src/main/java/de/jplag/cli/CLI.java
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,8 @@ private String getResultFileBaseName() {
private String getOffsetFileName(int offset) {
if (offset <= 0) {
return getResultFilePath();
} else {
return getResultFileBaseName() + "(" + offset + ")" + DEFAULT_FILE_ENDING;
}
return getResultFileBaseName() + "(" + offset + ")" + DEFAULT_FILE_ENDING;
}

private String getWritableFileName() throws CliException {
Expand Down
19 changes: 9 additions & 10 deletions cli/src/main/java/de/jplag/cli/logger/CliProgressBarProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,16 @@ public class CliProgressBarProvider implements ProgressBarProvider {

@Override
public ProgressBar initProgressBar(ProgressBarType type, int totalSteps) {
if (allowedLogLevels.contains(CollectedLogger.getLogLevel())) {
if (type.isIdleBar()) {
IdleBar idleBar = new IdleBar(type.getDefaultText());
idleBar.start();
return idleBar;
}
me.tongfei.progressbar.ProgressBar progressBar = new ProgressBarBuilder().setTaskName(type.getDefaultText()).setInitialMax(totalSteps)
.setStyle(ProgressBarStyle.ASCII).build();
return new TongfeiProgressBar(progressBar);
} else {
if (!allowedLogLevels.contains(CollectedLogger.getLogLevel())) {
return new VoidProgressBar();
}
if (type.isIdleBar()) {
IdleBar idleBar = new IdleBar(type.getDefaultText());
idleBar.start();
return idleBar;
}
me.tongfei.progressbar.ProgressBar progressBar = new ProgressBarBuilder().setTaskName(type.getDefaultText()).setInitialMax(totalSteps)
.setStyle(ProgressBarStyle.ASCII).build();
return new TongfeiProgressBar(progressBar);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public boolean parse() throws CliException {
try {
this.parseResult = this.commandLine.parseArgs(args);
if (this.parseResult.isUsageHelpRequested()
|| (this.parseResult.subcommand() != null && this.parseResult.subcommand().isUsageHelpRequested())) {
|| this.parseResult.subcommand() != null && this.parseResult.subcommand().isUsageHelpRequested()) {
commandLine.getExecutionStrategy().execute(this.parseResult);
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public CommandLine.Help.Ansi.Text renderParameterLabel(CommandLine.Model.ArgSpec
List<CommandLine.Help.Ansi.IStyle> styles) {
if (argSpec.type().isEnum()) {
Object[] enumConstants = argSpec.type().getEnumConstants();
String enumValueNames = Arrays.stream(enumConstants).map(enumConstant -> (Enum.class.cast(enumConstant)).name())
String enumValueNames = Arrays.stream(enumConstants).map(enumConstant -> Enum.class.cast(enumConstant).name())
.collect(Collectors.joining(VALUE_SEPARATOR));
return CommandLine.Help.Ansi.AUTO.text(String.format(PARAM_LABEL_PATTERN, enumValueNames));
}
Expand Down
2 changes: 1 addition & 1 deletion cli/src/test/java/de/jplag/cli/MinTokenMatchTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ void testInvalidInput() {

@Test
void testUpperBound() {
String higherThanMax = String.valueOf(((long) Integer.MAX_VALUE) + 1);
String higherThanMax = String.valueOf((long) Integer.MAX_VALUE + 1);

Assertions.assertThrowsExactly(CliException.class, () -> {
runCli(options -> options.withInvalid(CliArgument.MIN_TOKEN_MATCH, higherThanMax));
Expand Down
2 changes: 1 addition & 1 deletion cli/src/test/java/de/jplag/cli/logger/IdleBarTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ private void checkIdleBarOutput(String output, int frameIndex, int numberOfSpace

String[] timeParts = time.split(":");
int seconds = Integer.parseInt(timeParts[0]) * 60 * 60 + Integer.parseInt(timeParts[1]) * 60 + Integer.parseInt(timeParts[2]);
int expectedTime = (int) ((IDLE_BAR_ANIMATION_DELAY * frameIndex) / 1000);
int expectedTime = (int) (IDLE_BAR_ANIMATION_DELAY * frameIndex / 1000);
Assertions.assertTrue(Math.abs(seconds - expectedTime) < 1, "Frame time of by more than one second");
}
}
9 changes: 4 additions & 5 deletions cli/src/test/java/de/jplag/cli/test/CliArgumentBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,11 @@ private String[] formatArgNameAndValue(String name, Object value) {
} else {
return new String[] {SHORT_OPTION_PREFIX + name, valueText};
}
}
if (valueText.isEmpty()) {
return new String[] {LONG_OPTION_PREFIX + name};
} else {
if (valueText.isEmpty()) {
return new String[] {LONG_OPTION_PREFIX + name};
} else {
return new String[] {LONG_OPTION_PREFIX + name + "=" + formatArgValue(value)};
}
return new String[] {LONG_OPTION_PREFIX + name + "=" + formatArgValue(value)};
}
}

Expand Down
11 changes: 8 additions & 3 deletions cli/src/test/java/de/jplag/cli/test/CliTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@

import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.ArgumentMatchers;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.slf4j.event.Level;

import de.jplag.JPlagResult;
import de.jplag.cli.*;
import de.jplag.cli.CLI;
import de.jplag.cli.JPlagOptionsBuilder;
import de.jplag.cli.JPlagRunner;
import de.jplag.cli.OutputFileGenerator;
import de.jplag.cli.logger.CollectedLogger;
import de.jplag.cli.picocli.CliInputHandler;
import de.jplag.exceptions.ExitException;
Expand Down Expand Up @@ -140,8 +144,9 @@ protected Level runCliForLogLevel(Consumer<CliArgumentBuilder> additionalOptions
protected CliResult runCli(Consumer<CliArgumentBuilder> additionalOptionsBuilder) throws ExitException, IOException {
try (MockedStatic<JPlagRunner> runnerMock = Mockito.mockStatic(JPlagRunner.class);
MockedStatic<OutputFileGenerator> generatorMock = Mockito.mockStatic(OutputFileGenerator.class)) {
runnerMock.when(() -> JPlagRunner.runJPlag(Mockito.any())).thenReturn(new JPlagResult(Collections.emptyList(), null, 1, null));
generatorMock.when(() -> OutputFileGenerator.generateJPlagResultZip(Mockito.any(), Mockito.any())).then(invocationOnMock -> null);
runnerMock.when(() -> JPlagRunner.runJPlag(ArgumentMatchers.any())).thenReturn(new JPlagResult(Collections.emptyList(), null, 1, null));
generatorMock.when(() -> OutputFileGenerator.generateJPlagResultZip(ArgumentMatchers.any(), ArgumentMatchers.any()))
.then(invocationOnMock -> null);

CliArgumentBuilder copy = this.defaultArgumentBuilder.copy();
additionalOptionsBuilder.accept(copy);
Expand Down
8 changes: 4 additions & 4 deletions core/src/main/java/de/jplag/GreedyStringTiling.java
Original file line number Diff line number Diff line change
Expand Up @@ -212,22 +212,22 @@ private boolean[] calculateInitiallyMarked(Submission submission) {
List<Token> tokens = submission.getTokenList();
boolean[] result = new boolean[tokens.size()];
for (int i = 0; i < result.length; i++) {
result[i] = tokens.get(i).getType().isExcludedFromMatching() || (baseCodeTokens != null && baseCodeTokens.contains(tokens.get(i)));
result[i] = tokens.get(i).getType().isExcludedFromMatching() || baseCodeTokens != null && baseCodeTokens.contains(tokens.get(i));
}
return result;
}

private SubsequenceHashLookupTable subsequenceHashLookupTableForSubmission(Submission submission, boolean[] marked) {
return cachedHashLookupTables.computeIfAbsent(submission,
(key -> new SubsequenceHashLookupTable(minimumMatchLength, tokenValueListFromSubmission(key), marked)));
key -> new SubsequenceHashLookupTable(minimumMatchLength, tokenValueListFromSubmission(key), marked));
}

/**
* Converts the tokens of the submission to a list of values.
* @param submission The submission from which to convert the tokens.
*/
private int[] tokenValueListFromSubmission(Submission submission) {
return cachedTokenValueLists.computeIfAbsent(submission, (key -> {
return cachedTokenValueLists.computeIfAbsent(submission, key -> {
List<Token> tokens = key.getTokenList();
int[] tokenValueList = new int[tokens.size()];
for (int i = 0; i < tokens.size(); i++) {
Expand All @@ -238,7 +238,7 @@ private int[] tokenValueListFromSubmission(Submission submission) {
tokenValueList[i] = tokenTypeValues.get(type);
}
return tokenValueList;
}));
});
}

private boolean checkMark(boolean[] marks, int index, Submission submission, Submission otherSubmission) {
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/de/jplag/JPlagComparison.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,6 @@ public String toString() {
}

private double similarity(int divisor) {
return (divisor == 0 ? 0.0 : (getNumberOfMatchedTokens() / (double) divisor));
return divisor == 0 ? 0.0 : getNumberOfMatchedTokens() / (double) divisor;
}
}
2 changes: 1 addition & 1 deletion core/src/main/java/de/jplag/JPlagResult.java
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public int[] getSimilarityDistribution() {
* the same distribution as {@link JPlagResult#getSimilarityDistribution()}
*/
public int[] getMaxSimilarityDistribution() {
return calculateDistributionFor(comparisons, (JPlagComparison::maximalSimilarity));
return calculateDistributionFor(comparisons, JPlagComparison::maximalSimilarity);
}

public List<ClusteringResult<Submission>> getClusteringResult() {
Expand Down
8 changes: 4 additions & 4 deletions core/src/main/java/de/jplag/Match.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ public record Match(int startOfFirst, int startOfSecond, int length) {
*/
public boolean overlaps(Match other) {
if (startOfFirst < other.startOfFirst) {
if ((other.startOfFirst - startOfFirst) < length) {
if (other.startOfFirst - startOfFirst < length) {
return true;
}
} else if ((startOfFirst - other.startOfFirst) < other.length) {
} else if (startOfFirst - other.startOfFirst < other.length) {
return true;
}

if (startOfSecond < other.startOfSecond) {
return (other.startOfSecond - startOfSecond) < length;
return other.startOfSecond - startOfSecond < length;
}
return (startOfSecond - other.startOfSecond) < other.length;
return startOfSecond - other.startOfSecond < other.length;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/de/jplag/SubmissionSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ private void parseSubmissions(List<Submission> submissions) throws LanguageExcep

int validSubmissions = submissions.size() - errors;
logger.debug("{} submissions parsed successfully!", validSubmissions);
logger.debug("{} parser error{}!", errors, (errors != 1 ? "s" : ""));
logger.debug("{} parser error{}!", errors, errors != 1 ? "s" : "");
}

}
4 changes: 2 additions & 2 deletions core/src/main/java/de/jplag/SubmissionSetBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public SubmissionSet buildSubmissionSet() throws ExitException {
// For backward compatibility, don't prefix submission names with their root directory
// if there is only one root directory.
int numberOfRootDirectories = submissionDirectories.size() + oldSubmissionDirectories.size();
boolean multipleRoots = (numberOfRootDirectories > 1);
boolean multipleRoots = numberOfRootDirectories > 1;

List<SubmissionFileData> submissionFiles = new ArrayList<>();
for (File submissionDirectory : submissionDirectories) {
Expand Down Expand Up @@ -225,7 +225,7 @@ private void processSubmissionFile(SubmissionFileData file, boolean multipleRoot
} else if (file.submissionFile().isFile() && !hasValidSuffix(file.submissionFile())) {
logger.error("Ignore submission with invalid suffix: {}", file.submissionFile().getName());
} else {
String rootDirectoryPrefix = multipleRoots ? (file.root().getName() + File.separator) : "";
String rootDirectoryPrefix = multipleRoots ? file.root().getName() + File.separator : "";
String submissionName = rootDirectoryPrefix + file.submissionFile().getName();
Submission submission = processSubmission(submissionName, file.submissionFile(), file.isNew());
foundSubmissions.put(submission.getRoot(), submission);
Expand Down
4 changes: 2 additions & 2 deletions core/src/main/java/de/jplag/SubsequenceHashLookupTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ List<Integer> startIndexesOfPossiblyMatchingSubsequencesForSubsequenceHash(int s
private void computeSubsequenceHashes(boolean[] marked) {
int hash = 0;
int hashedLength = 0;
int factor = (windowSize != 1 ? (2 << (windowSize - 2)) : 1);
int factor = windowSize != 1 ? 2 << windowSize - 2 : 1;

for (int windowEndIndex = 0; windowEndIndex < values.length; windowEndIndex++) {
int windowStartIndex = windowEndIndex - windowSize;
Expand All @@ -87,7 +87,7 @@ private void computeSubsequenceHashes(boolean[] marked) {
}
hash -= factor * hashValueForValue(values[windowStartIndex]);
}
hash = (2 * hash) + hashValueForValue(values[windowEndIndex]);
hash = 2 * hash + hashValueForValue(values[windowEndIndex]);
if (marked[windowEndIndex]) {
hashedLength = 0;
} else {
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/de/jplag/clustering/Cluster.java
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ private double averageSimilarity(BiFunction<T, T, Double> similarity) {

private int connections() {
int size = members.size();
return ((size - 1) * size) / 2;
return (size - 1) * size / 2;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ private static double calculateAverageSimilarityFor(Collection<Integer> cluster,
}
}
int nMinusOne = cluster.size() - 1;
double numberOfComparisons = (nMinusOne * (nMinusOne + 1)) / 2.0;
double numberOfComparisons = nMinusOne * (nMinusOne + 1) / 2.0;
/*
* Use Gauss sum to calculate number of comparisons in cluster: Given cluster of size n we need Gauss sum of n-1
* comparisons: compare first element of cluster to all other except itself: n-1 comparisons. compare second element to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class CumulativeDistributionFunctionPreprocessor implements ClusteringPre
@Override
public double[][] preprocessSimilarities(double[][] similarityMatrix) {
RealMatrix similarity = new Array2DRowRealMatrix(similarityMatrix, true);
int connections = (similarity.getColumnDimension() * (similarity.getColumnDimension() - 1)) / 2;
int connections = similarity.getColumnDimension() * (similarity.getColumnDimension() - 1) / 2;
EmpiricalDistribution dist = new EmpiricalDistribution(Math.max(100, connections / 100));
double[] allWeights = new double[connections];
similarity.walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public PercentileThresholdProcessor(double percentile) {
public double[][] preprocessSimilarities(double[][] similarityMatrix) {
Array2DRowRealMatrix similarity = new Array2DRowRealMatrix(similarityMatrix, false);
Percentile percentileEstimator = new Percentile().withEstimationType(EstimationType.R_2);
int connections = (similarity.getColumnDimension() * (similarity.getColumnDimension() - 1)) / 2;
int connections = similarity.getColumnDimension() * (similarity.getColumnDimension() - 1) / 2;
double[] allWeights = new double[connections];
similarity.walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() {

Expand Down
4 changes: 2 additions & 2 deletions core/src/main/java/de/jplag/merging/MatchMerging.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ private List<Neighbor> computeNeighbors(List<Match> globalMatches) {
sortedByRight.sort(Comparator.comparingInt(Match::startOfSecond));

for (int i = 0; i < sortedByLeft.size() - 1; i++) {
if (sortedByRight.indexOf(sortedByLeft.get(i)) == (sortedByRight.indexOf(sortedByLeft.get(i + 1)) - 1)) {
if (sortedByRight.indexOf(sortedByLeft.get(i)) == sortedByRight.indexOf(sortedByLeft.get(i + 1)) - 1) {
neighbors.add(new Neighbor(sortedByLeft.get(i), sortedByLeft.get(i + 1)));
}
}
Expand Down Expand Up @@ -159,7 +159,7 @@ private boolean mergeOverlapsFiles(Submission leftSubmission, Submission rightSu
* @return true if FILE_END is in token
*/
private boolean containsFileEndToken(List<Token> token) {
return token.stream().map(Token::getType).anyMatch(it -> it.equals(SharedTokenType.FILE_END));
return token.stream().map(Token::getType).anyMatch(SharedTokenType.FILE_END::equals);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/de/jplag/options/JPlagOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ private Integer normalizeMaximumNumberOfComparisons(Integer maximumNumberOfCompa
}

private Integer normalizeMinimumTokenMatch(Integer minimumTokenMatch) {
return (minimumTokenMatch != null && minimumTokenMatch < 1) ? Integer.valueOf(1) : minimumTokenMatch;
return minimumTokenMatch != null && minimumTokenMatch < 1 ? Integer.valueOf(1) : minimumTokenMatch;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ private void writeOverview(JPlagResult result) {
int totalComparisons = result.getAllComparisons().size();
int numberOfMaximumComparisons = result.getOptions().maximumNumberOfComparisons();
int shownComparisons = Math.min(totalComparisons, numberOfMaximumComparisons);
int missingComparisons = totalComparisons > numberOfMaximumComparisons ? (totalComparisons - numberOfMaximumComparisons) : 0;
int missingComparisons = totalComparisons > numberOfMaximumComparisons ? totalComparisons - numberOfMaximumComparisons : 0;
logger.info("Total Comparisons: {}. Comparisons in Report: {}. Omitted Comparisons: {}.", totalComparisons, shownComparisons,
missingComparisons);
OverviewReport overviewReport = new OverviewReport(REPORT_VIEWER_VERSION, folders.stream().map(File::getPath).toList(), // submissionFolderPath
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ protected Optional<JPlagComparison> compareSubmissions(Submission first, Submiss
private List<SubmissionTuple> buildComparisonTuples(List<Submission> submissions) {
List<SubmissionTuple> tuples = new ArrayList<>();

for (int i = 0; i < (submissions.size() - 1); i++) {
for (int i = 0; i < submissions.size() - 1; i++) {
Submission first = submissions.get(i);
for (int j = (i + 1); j < submissions.size(); j++) {
for (int j = i + 1; j < submissions.size(); j++) {
Submission second = submissions.get(j);
if (first.isNew() || second.isNew()) {
tuples.add(new SubmissionTuple(first, second));
Expand Down
2 changes: 1 addition & 1 deletion core/src/test/java/de/jplag/BasicFunctionalityTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ void testPartialPlagiarism() throws ExitException {

// All comparisons with E shall have no matches
result.getAllComparisons().stream()
.filter(comparison -> comparison.secondSubmission().getName().equals("E") || comparison.firstSubmission().getName().equals("E"))
.filter(comparison -> "E".equals(comparison.secondSubmission().getName()) || "E".equals(comparison.firstSubmission().getName()))
.forEach(comparison -> assertEquals(0, comparison.similarity(), DELTA));

// Hard coded assertions on selected comparisons
Expand Down
3 changes: 2 additions & 1 deletion core/src/test/java/de/jplag/InvalidSubmissionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ void testInvalidSubmissionsWithDebug() throws ExitException {
File errorFolder = new File(Path.of("errors", "java").toString());
assertTrue(errorFolder.exists());
String[] errorSubmissions = errorFolder.list();
if (errorSubmissions != null)
if (errorSubmissions != null) {
Arrays.sort(errorSubmissions); // File systems don't promise alphabetical order.
}
deleteDirectory(errorFolder.getParentFile());
assertArrayEquals(new String[] {"A", "B"}, errorSubmissions);
}
Expand Down
Loading
Loading