Просмотр исходного кода

ReportViewer - Save File Lines as Indices to LookUpTable

Nesta Bentum 4 лет назад
Родитель
Сommit
de9ab29709

+ 2 - 11
jplag/src/main/java/de/jplag/reporting/JsonReport.java

@@ -1,28 +1,19 @@
 package de.jplag.reporting;
 
 import java.io.File;
-import java.util.List;
 
 import de.jplag.JPlagResult;
 import de.jplag.reporting.jsonfactory.JsonFactory;
 import de.jplag.reporting.reportobject.ReportObjectFactory;
 import de.jplag.reporting.reportobject.model.JPlagReport;
 
-// ReportImplementation -> JsonReport
-
 /**
  * A report generator which reports the JPlagResult in Json format.
  */
 public class JsonReport implements Report {
 
     @Override
-    public List<String> getReportStrings(JPlagResult result) {
-        JPlagReport report = ReportObjectFactory.getReportObject(result);
-        return JsonFactory.getJsonStrings(report);
-    }
-
-    @Override
-    public boolean saveReport(JPlagResult result, String path) {
+    public void saveReport(JPlagResult result, String path) {
         JPlagReport report = ReportObjectFactory.getReportObject(result);
         File directory = new File(path);
         if (!directory.exists()) {
@@ -30,7 +21,7 @@ public class JsonReport implements Report {
                 logger.error("Failed to create dir.");
             }
         }
-        return JsonFactory.saveJsonFiles(report, path);
+        JsonFactory.saveJsonFiles(report, path);
     }
 
 }

+ 1 - 14
jplag/src/main/java/de/jplag/reporting/Report.java

@@ -1,14 +1,10 @@
 package de.jplag.reporting;
 
-import java.util.List;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import de.jplag.JPlagResult;
 
-// ReportStrategy -> Report
-
 /**
  * Strategy interface for reporting. A report generator should implement this interface.
  */
@@ -16,19 +12,10 @@ public interface Report {
 
     Logger logger = LoggerFactory.getLogger(Report.class);
 
-    /**
-     * This function returns a list containing the report objects as simple strings. The first element is the string of the
-     * overview object. Each following element is a string of a comparison report object.
-     * @param result The result of a JPlag comparison
-     * @return A list containing report objects to string. First element is Overview. Other elements are comparisons.
-     */
-    List<String> getReportStrings(JPlagResult result);
-
     /**
      * Creates and saves JPlag report files to the disk.
      * @param result The result of a JPlag comparison.
      * @param path Path to the directory where the report should be saved.
-     * @return True if the process is successful, otherwise false.
      */
-    boolean saveReport(JPlagResult result, String path);
+    void saveReport(JPlagResult result, String path);
 }

+ 2 - 27
jplag/src/main/java/de/jplag/reporting/jsonfactory/JsonFactory.java

@@ -2,13 +2,10 @@ package de.jplag.reporting.jsonfactory;
 
 import java.io.IOException;
 import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.List;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 
 import de.jplag.reporting.reportobject.model.ComparisonReport;
@@ -21,42 +18,20 @@ public class JsonFactory {
 
     private static final Logger logger = LoggerFactory.getLogger(JsonFactory.class);
 
-    private static final ObjectMapper mapper = new ObjectMapper();
-
-    /**
-     * Uses Jackson to create Json Strings from JPlagReport object.
-     * @return A list, first element is Json String of Overview object. The rest elements are Json Strings of Comparison
-     * objects.
-     */
-    public static List<String> getJsonStrings(JPlagReport jPlagReport) {
-        List<String> jsonReports = new ArrayList<>();
-        try {
-            jsonReports.add(mapper.writeValueAsString(jPlagReport.overviewReport()));
-            for (ComparisonReport comparisonReport : jPlagReport.comparisons()) {
-                jsonReports.add(mapper.writeValueAsString(comparisonReport));
-            }
-        } catch (JsonProcessingException e) {
-            logger.error("Error converting object to json " + e.getMessage(), e);
-        }
-        return jsonReports;
-    }
-
     /**
      * Creates Json Files for the given JPlagReport and saves them in the given folder.
-     * @return A boolean, representing whether the process was successful.
      */
-    public static boolean saveJsonFiles(JPlagReport jPlagReport, String folderPath) {
+    public static void saveJsonFiles(JPlagReport jPlagReport, String folderPath) {
         try {
             ObjectMapper mapper = new ObjectMapper();
             mapper.writeValue(Path.of(folderPath, "overview.json").toFile(), jPlagReport.overviewReport());
+            mapper.writeValue(Path.of(folderPath, "lookUpTable.json").toFile(), jPlagReport.lineLookUpTable());
             for (ComparisonReport report : jPlagReport.comparisons()) {
                 String name = report.firstSubmissionId().concat("-").concat(report.secondSubmissionId()).concat(".json");
                 mapper.writeValue(Path.of(folderPath, name).toFile(), report);
             }
         } catch (IOException e) {
             logger.error("Failed to save json files: " + e.getMessage(), e);
-            return false;
         }
-        return true;
     }
 }

+ 11 - 80
jplag/src/main/java/de/jplag/reporting/reportobject/ReportObjectFactory.java

@@ -1,32 +1,29 @@
 package de.jplag.reporting.reportobject;
 
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashSet;
 import java.util.List;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import de.jplag.*;
+import de.jplag.JPlagComparison;
+import de.jplag.JPlagResult;
 import de.jplag.reporting.reportobject.mapper.ClusteringResultMapper;
+import de.jplag.reporting.reportobject.mapper.ComparisonReportMapper;
 import de.jplag.reporting.reportobject.mapper.MetricMapper;
-import de.jplag.reporting.reportobject.model.*;
-import de.jplag.reporting.reportobject.model.Match;
+import de.jplag.reporting.reportobject.model.ComparisonReport;
+import de.jplag.reporting.reportobject.model.JPlagReport;
+import de.jplag.reporting.reportobject.model.Metric;
+import de.jplag.reporting.reportobject.model.OverviewReport;
 
 /**
  * Factory class, responsible for converting a JPlagResult object to Overview and Comparison DTO classes.
  */
 public class ReportObjectFactory {
 
-    private static final Logger logger = LoggerFactory.getLogger(ReportObjectFactory.class);
     private static final ClusteringResultMapper clusteringResultMapper = new ClusteringResultMapper();
     private static final MetricMapper metricMapper = new MetricMapper();
+    private static final ComparisonReportMapper comparisonReportMapper = new ComparisonReportMapper();
 
     /**
      * Converts a JPlagResult to a JPlagReport.
@@ -34,8 +31,9 @@ public class ReportObjectFactory {
      */
     public static JPlagReport getReportObject(JPlagResult result) {
         OverviewReport overviewReport = generateOverviewReport(result);
-        List<ComparisonReport> comparisons = generateComparisonReports(result);
-        return new JPlagReport(overviewReport, comparisons);
+        var comparisonReportMapperResult = comparisonReportMapper.generateComparisonReports(result);
+        List<ComparisonReport> comparisons = comparisonReportMapperResult.comparisonReports();
+        return new JPlagReport(overviewReport, comparisons, comparisonReportMapperResult.lineLookupTable());
     }
 
     /**
@@ -69,33 +67,11 @@ public class ReportObjectFactory {
         return overviewReport;
     }
 
-    /**
-     * Generates detailed ComparisonReport DTO for each comparison in a JPlagResult.
-     * @return A list with ComparisonReport DTOs.
-     */
-    private static List<ComparisonReport> generateComparisonReports(JPlagResult result) {
-        List<ComparisonReport> comparisons = new ArrayList<>();
-        getComparisons(result).forEach(comparison -> comparisons.add( //
-                new ComparisonReport(comparison.getFirstSubmission().getName(), //
-                        comparison.getSecondSubmission().getName(), //
-                        comparison.similarity(), //
-                        getFilesForSubmission(comparison.getFirstSubmission()), //
-                        getFilesForSubmission(comparison.getSecondSubmission()), //
-                        convertMatchesToReportMatches(result, comparison, comparison.getMatches()) //
-                )));
-        return comparisons;
-    }
-
     private static List<JPlagComparison> getComparisons(JPlagResult result) {
         int numberOfComparisons = result.getOptions().getMaximumNumberOfComparisons();
         return result.getComparisons(numberOfComparisons);
     }
 
-    private static List<Match> convertMatchesToReportMatches(JPlagResult result, JPlagComparison comparison, List<de.jplag.Match> matches) {
-        return matches.stream().map(match -> convertMatchToReportMatch(comparison, match, !result.getOptions().getLanguage().supportsColumns()))
-                .toList();
-    }
-
     /**
      * Gets the names of all submissions.
      * @return A list containing all submission names.
@@ -129,51 +105,6 @@ public class ReportObjectFactory {
         return List.of(metricMapper.getAverageMetric(result), metricMapper.getMaxMetric(result));
     }
 
-    /**
-     * Converts files of a submission to FilesOFSubmission DTO.
-     * @return A list containing FilesOfSubmission DTOs.
-     */
-    private static List<FilesOfSubmission> getFilesForSubmission(Submission submission) {
-        return submission.getFiles().stream().map(file -> new FilesOfSubmission(file.getName(), readFileLines(file))).toList();
-    }
-
-    /**
-     * Converts a JPlag Match object to a Match DTO.
-     * @param comparison The comparison from which the match originates.
-     * @param match The match to be converted.
-     * @param usesIndex Indicates whether the language uses indexes.
-     * @return A Match DTO.
-     */
-    private static Match convertMatchToReportMatch(JPlagComparison comparison, de.jplag.Match match, boolean usesIndex) {
-        TokenList tokensFirst = comparison.getFirstSubmission().getTokenList();
-        TokenList tokensSecond = comparison.getSecondSubmission().getTokenList();
-        Token startTokenFirst = tokensFirst.getToken(match.startOfFirst());
-        Token endTokenFirst = tokensFirst.getToken(match.startOfFirst() + match.length() - 1);
-        Token startTokenSecond = tokensSecond.getToken(match.startOfSecond());
-        Token endTokenSecond = tokensSecond.getToken(match.startOfSecond() + match.length() - 1);
-
-        int startFirst = usesIndex ? startTokenFirst.getIndex() : startTokenFirst.getLine();
-        int endFirst = usesIndex ? endTokenFirst.getIndex() : endTokenFirst.getLine();
-        int startSecond = usesIndex ? startTokenSecond.getIndex() : startTokenSecond.getLine();
-        int endSecond = usesIndex ? endTokenSecond.getIndex() : endTokenSecond.getLine();
-        int tokens = match.length();
-
-        return new Match(startTokenFirst.getFile(), startTokenSecond.getFile(), startFirst, endFirst, startSecond, endSecond, tokens);
-    }
-
-    private static List<String> readFileLines(File file) {
-        List<String> lines = new ArrayList<>();
-        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
-            String line;
-            while ((line = bufferedReader.readLine()) != null) {
-                lines.add(line);
-            }
-        } catch (IOException exception) {
-            logger.error("Could not read file: " + exception.getMessage(), exception);
-        }
-        return lines;
-    }
-
     private static String getDate() {
         SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
         Date date = new Date();

+ 107 - 0
jplag/src/main/java/de/jplag/reporting/reportobject/mapper/ComparisonReportMapper.java

@@ -0,0 +1,107 @@
+package de.jplag.reporting.reportobject.mapper;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import de.jplag.*;
+import de.jplag.reporting.reportobject.model.ComparisonReport;
+import de.jplag.reporting.reportobject.model.FilesOfSubmission;
+import de.jplag.reporting.reportobject.model.Match;
+
+public class ComparisonReportMapper {
+
+    private static final Logger logger = LoggerFactory.getLogger(ComparisonReportMapper.class);
+    private final HashMap<Long, String> lineLookUpTable = new HashMap<>();
+    private long currentLineIndex;
+
+    /**
+     * Generates detailed ComparisonReport DTO for each comparison in a JPlagResult.
+     * @param jPlagResult The JPlagResult to generate the comparison reports from.
+     * @return A ComparisonReportMapperResult consisting of two DTOs: the list of ComparisonsReport. A ComparisonReport
+     * contains information about a comparison between two submission - including their files. These files are not saved in
+     * plain text though, they are saved as numbers. these numbers are indices to the second DTO of the
+     * ComparisonReportMapperResult, the lineLookUpTable.
+     */
+    public ComparisonReportMapperResult generateComparisonReports(JPlagResult jPlagResult) {
+        List<ComparisonReport> comparisons = new ArrayList<>();
+        int maxNumOfComparisons = jPlagResult.getOptions().getMaximumNumberOfComparisons();
+        jPlagResult.getComparisons(maxNumOfComparisons).forEach(comparison -> comparisons.add( //
+                new ComparisonReport(comparison.getFirstSubmission().getName(), //
+                        comparison.getSecondSubmission().getName(), //
+                        comparison.similarity(), //
+                        getFilesForSubmission(comparison.getFirstSubmission()), //
+                        getFilesForSubmission(comparison.getSecondSubmission()), //
+                        convertMatchesToReportMatches(jPlagResult, comparison) //
+                )));
+        return new ComparisonReportMapperResult(comparisons, lineLookUpTable);
+    }
+
+    private List<FilesOfSubmission> getFilesForSubmission(Submission submission) {
+        return submission.getFiles().stream().map(file -> new FilesOfSubmission(file.getName(), readFileLines(file))).collect(Collectors.toList());
+    }
+
+    private List<Long> readFileLines(File file) {
+        List<Long> lineIndices = new ArrayList<>();
+        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
+            String line;
+            while ((line = bufferedReader.readLine()) != null) {
+                if (!lineLookUpTable.containsValue(line)) {
+                    lineLookUpTable.put(currentLineIndex, line);
+                    lineIndices.add(currentLineIndex);
+                    currentLineIndex++;
+                } else {
+                    lineIndices.add(getIndexOfLine(line));
+                }
+            }
+        } catch (IOException exception) {
+            logger.error("Could not read file: " + exception.getMessage());
+        }
+        return lineIndices;
+    }
+
+    private Long getIndexOfLine(String line) {
+        return lineLookUpTable.entrySet().stream().filter(entry -> Objects.equals(entry.getValue(), line)).map(Map.Entry::getKey).findFirst()
+                .orElseThrow();
+    }
+
+    private List<Match> convertMatchesToReportMatches(JPlagResult result, JPlagComparison comparison) {
+        return comparison.getMatches().stream()
+                .map(match -> convertMatchToReportMatch(comparison, match, result.getOptions().getLanguage().usesIndex()))
+                .collect(Collectors.toList());
+    }
+
+    /**
+     * Converts a JPlag Match object to a Match DTO.
+     * @param comparison The comparison from which the match originates.
+     * @param match The match to be converted.
+     * @param usesIndex Indicates whether the language uses indexes.
+     * @return A Match DTO.
+     */
+    private Match convertMatchToReportMatch(JPlagComparison comparison, de.jplag.Match match, Boolean usesIndex) {
+        TokenList tokensFirst = comparison.getFirstSubmission().getTokenList();
+        TokenList tokensSecond = comparison.getSecondSubmission().getTokenList();
+        Token startTokenFirst = tokensFirst.getToken(match.getStartOfFirst());
+        Token endTokenFirst = tokensFirst.getToken(match.getStartOfFirst() + match.getLength() - 1);
+        Token startTokenSecond = tokensSecond.getToken(match.getStartOfSecond());
+        Token endTokenSecond = tokensSecond.getToken(match.getStartOfSecond() + match.getLength() - 1);
+
+        int startFirst = usesIndex ? startTokenFirst.getIndex() : startTokenFirst.getLine();
+        int endFirst = usesIndex ? endTokenFirst.getIndex() : endTokenFirst.getLine();
+        int startSecond = usesIndex ? startTokenSecond.getIndex() : startTokenSecond.getLine();
+        int endSecond = usesIndex ? endTokenSecond.getIndex() : endTokenSecond.getLine();
+        int tokens = match.getLength();
+
+        return new Match(startTokenFirst.getFile(), startTokenSecond.getFile(), startFirst, endFirst, startSecond, endSecond, tokens);
+    }
+
+    public record ComparisonReportMapperResult(List<ComparisonReport> comparisonReports, Map<Long, String> lineLookupTable) {
+    }
+
+}

+ 0 - 1
jplag/src/main/java/de/jplag/reporting/reportobject/model/ComparisonReport.java

@@ -10,7 +10,6 @@ public record ComparisonReport(@JsonProperty("first_submission_id") String first
         @JsonProperty("files_of_second_submission") List<FilesOfSubmission> filesOfSecondSubmission, @JsonProperty("matches") List<Match> matches) {
     public ComparisonReport(String firstSubmissionId, String secondSubmissionId, float matchPercentage,
             List<FilesOfSubmission> filesOfFirstSubmission, List<FilesOfSubmission> filesOfSecondSubmission, List<Match> matches) {
-
         this.firstSubmissionId = firstSubmissionId;
         this.secondSubmissionId = secondSubmissionId;
         this.matchPercentage = matchPercentage;

+ 3 - 19
jplag/src/main/java/de/jplag/reporting/reportobject/model/FilesOfSubmission.java

@@ -4,25 +4,9 @@ import java.util.List;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
 
-public class FilesOfSubmission {
-
-    @JsonProperty("file_name")
-    private final String fileName;
-
-    @JsonProperty("lines")
-    private final List<String> lines;
-
-    public FilesOfSubmission(String fileName, List<String> fileCode) {
+public record FilesOfSubmission(@JsonProperty("file_name") String fileName, @JsonProperty("lines") List<Long> lines) {
+    public FilesOfSubmission(String fileName, List<Long> lines) {
         this.fileName = fileName;
-        this.lines = List.copyOf(fileCode);
-    }
-
-    public String getFileName() {
-        return fileName;
-    }
-
-    public List<String> getLines() {
-        return lines;
+        this.lines = List.copyOf(lines);
     }
-
 }

+ 2 - 5
jplag/src/main/java/de/jplag/reporting/reportobject/model/JPlagReport.java

@@ -1,10 +1,7 @@
 package de.jplag.reporting.reportobject.model;
 
 import java.util.List;
+import java.util.Map;
 
-public record JPlagReport(OverviewReport overviewReport, List<ComparisonReport> comparisons) {
-    public JPlagReport(OverviewReport overviewReport, List<ComparisonReport> comparisons) {
-        this.overviewReport = overviewReport;
-        this.comparisons = List.copyOf(comparisons);
-    }
+public record JPlagReport(OverviewReport overviewReport, List<ComparisonReport> comparisons, Map<Long, String> lineLookUpTable) {
 }

+ 107 - 0
jplag/src/test/java/de/jplag/reporting/reportobject/mapper/ComparisonReportMapperTest.java

@@ -0,0 +1,107 @@
+package de.jplag.reporting.reportobject.mapper;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import de.jplag.JPlagComparison;
+import de.jplag.JPlagResult;
+import de.jplag.TestBase;
+import de.jplag.exceptions.ExitException;
+import de.jplag.reporting.reportobject.model.ComparisonReport;
+import de.jplag.reporting.reportobject.model.FilesOfSubmission;
+
+public class ComparisonReportMapperTest extends TestBase {
+
+    private final ComparisonReportMapper comparisonReportMapper = new ComparisonReportMapper();
+
+    @Test
+    public void test() throws ExitException {
+        // given
+
+        JPlagResult jPlagResult = runJPlagWithDefaultOptions("PartialPlagiarism");
+
+        // when
+        var actualMapperResult = comparisonReportMapper.generateComparisonReports(jPlagResult);
+        // then
+        assertSubmissionFilesAreCorrect(jPlagResult, actualMapperResult, "A", "B", "C", "D", "E");
+    }
+
+    private void assertSubmissionFilesAreCorrect(JPlagResult jPlagResult, ComparisonReportMapper.ComparisonReportMapperResult actualMapperResult,
+            String... submissionNames) {
+        for (String submissionName : submissionNames) { // per submission
+            Map<String, List<String>> fileNameToFileLinesExpected = getAllFilesOfSubmission(submissionName, jPlagResult); // collect all files in a
+                                                                                                                          // map [fileName]->
+                                                                                                                          // <linesOfFile>
+
+            var unresolvedLinesFilesActual = actualFilesOfSubmission(submissionName, actualMapperResult); // get all files of submission from mapping
+                                                                                                          // result.
+            // their lines are unresolved, so they are only numbers until we looked them up with the lineLookUpTable
+
+            for (FilesOfSubmission fileOfSubmissionActual : unresolvedLinesFilesActual) { // per mapped submissionFile
+                var resolvedLinesOfFile = fileOfSubmissionActual.lines().stream().map(actualMapperResult.lineLookupTable()::get).toList(); // resolve
+                                                                                                                                           // lines
+                                                                                                                                           // via
+                                                                                                                                           // lookup
+                var linesOfExpectedFile = fileNameToFileLinesExpected.get(fileOfSubmissionActual.fileName()); // fetch expected lines
+                Assertions.assertIterableEquals(linesOfExpectedFile, resolvedLinesOfFile); // compare
+            }
+        }
+
+    }
+
+    private List<FilesOfSubmission> actualFilesOfSubmission(String submissionName,
+            ComparisonReportMapper.ComparisonReportMapperResult actualMapperResult) {
+        return actualMapperResult.comparisonReports().stream().filter(comparisonReportContainsSubmission(submissionName)).findFirst()
+                .map(extractFilesOfSubmission(submissionName)).orElseThrow();
+    }
+
+    private Function<ComparisonReport, List<FilesOfSubmission>> extractFilesOfSubmission(String submissionName) {
+        return report -> report.secondSubmissionId().equals(submissionName) ? report.filesOfSecondSubmission() : report.filesOfFirstSubmission();
+    }
+
+    private Predicate<ComparisonReport> comparisonReportContainsSubmission(String submissionName) {
+        return comparisonReport -> comparisonReport.firstSubmissionId().equals(submissionName)
+                || comparisonReport.secondSubmissionId().equals(submissionName);
+    }
+
+    private Map<String, List<String>> getAllFilesOfSubmission(String submissionName, JPlagResult jPlagResult) {
+        return jPlagResult.getAllComparisons().stream().filter(comparisonContainsSubmission(submissionName)).findFirst()
+                .map(getFilesOfComparison(submissionName)).orElseThrow().stream().collect(Collectors.toMap(File::getName, this::readLines));
+    }
+
+    private Function<JPlagComparison, Collection<File>> getFilesOfComparison(String submissionName) {
+        return comparison -> comparison.getFirstSubmission().getName().equals(submissionName) ? comparison.getFirstSubmission().getFiles()
+                : comparison.getSecondSubmission().getFiles();
+    }
+
+    private Predicate<JPlagComparison> comparisonContainsSubmission(String submissionName) {
+        return comparison -> comparison.getFirstSubmission().getName().equals(submissionName)
+                || comparison.getSecondSubmission().getName().equals(submissionName);
+    }
+
+    private List<String> readLines(File file) {
+        List<String> lines = new ArrayList<>();
+
+        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
+            String line;
+            while ((line = bufferedReader.readLine()) != null) {
+                lines.add(line);
+            }
+        } catch (IOException ignored) {
+        }
+
+        return lines;
+    }
+}