Submission.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package de.jplag;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.nio.file.Files;
  10. import java.nio.file.Path;
  11. import java.util.ArrayList;
  12. import java.util.Collection;
  13. import java.util.List;
  14. import de.jplag.exceptions.ReportGenerationException;
  15. import de.jplag.options.JPlagOptions;
  16. /**
  17. * Represents a single submission. A submission can contain multiple files.
  18. */
  19. public class Submission implements Comparable<Submission> {
  20. /**
  21. * Directory name for storing submission files with parse errors if so requested.
  22. */
  23. private static final String ERROR_FOLDER = "errors";
  24. /**
  25. * Identification of the submission (often a directory or file name).
  26. */
  27. private final String name;
  28. /**
  29. * Root of the submission files (including the subdir if used).
  30. */
  31. private final File submissionRootFile;
  32. /**
  33. * Files of the submission.
  34. */
  35. private final Collection<File> files;
  36. /**
  37. * Whether an error occurred during parsing the submission files.
  38. */
  39. private boolean hasErrors;
  40. /**
  41. * Parse result, tokens from all files.
  42. */
  43. private TokenList tokenList;
  44. /**
  45. * Base code comparison
  46. */
  47. private JPlagComparison baseCodeComparison;
  48. private final Language language;
  49. private final ErrorCollector errorCollector;
  50. /**
  51. * Creates a submission.
  52. * @param name Identification of the submission (directory or filename).
  53. * @param submissionRootFile is the submission file, or the root of the submission itself.
  54. * @param files are the files of the submissions, if the root is a single file it should just contain one file.
  55. * @param language is the language of the submission.
  56. * @param errorCollector is the interface for error reporting.
  57. */
  58. public Submission(String name, File submissionRootFile, Collection<File> files, Language language, ErrorCollector errorCollector) {
  59. this.name = name;
  60. this.submissionRootFile = submissionRootFile;
  61. this.files = files;
  62. this.language = language;
  63. this.errorCollector = errorCollector;
  64. }
  65. /**
  66. * @return a list of files this submission consists of.
  67. */
  68. public Collection<File> getFiles() {
  69. return files;
  70. }
  71. /**
  72. * @return name of the submission (directory or file name).
  73. */
  74. public String getName() {
  75. return name;
  76. }
  77. /**
  78. * @return the unique file of the submission, which is either in a root folder or a subfolder of root folder when the
  79. * subdirectory option is used.
  80. */
  81. public File getRoot() {
  82. return submissionRootFile;
  83. }
  84. /**
  85. * @return Number of tokens in the parse result.
  86. */
  87. public int getNumberOfTokens() {
  88. if (tokenList == null) {
  89. return 0;
  90. }
  91. return tokenList.size();
  92. }
  93. /**
  94. * Sets the base code comparison
  95. * @param baseCodeComparison is submissions matches with the base code
  96. */
  97. public void setBaseCodeComparison(JPlagComparison baseCodeComparison) {
  98. this.baseCodeComparison = baseCodeComparison;
  99. }
  100. /**
  101. * @return base code comparison
  102. */
  103. public JPlagComparison getBaseCodeComparison() {
  104. return baseCodeComparison;
  105. }
  106. /**
  107. * @return Whether a comparison between the submission and the base code is available.
  108. */
  109. public boolean hasBaseCodeMatches() {
  110. return baseCodeComparison != null;
  111. }
  112. /**
  113. * @param subtractBaseCode If true subtract basecode matches if possible.
  114. * @return Similarity divisor for the submission.
  115. */
  116. public int getSimilarityDivisor(boolean subtractBaseCode) {
  117. int divisor = getNumberOfTokens() - getFiles().size();
  118. if (subtractBaseCode && baseCodeComparison != null) {
  119. divisor -= baseCodeComparison.getNumberOfMatchedTokens();
  120. }
  121. return divisor;
  122. }
  123. /**
  124. * @return Parse result of the submission.
  125. */
  126. public TokenList getTokenList() {
  127. return tokenList;
  128. }
  129. /**
  130. * @return true if at least one error occurred while parsing this submission; false otherwise.
  131. */
  132. public boolean hasErrors() {
  133. return hasErrors;
  134. }
  135. /**
  136. * Parse files of the submission.
  137. * @return Whether parsing was successful.
  138. */
  139. public boolean parse(boolean debugParser) {
  140. if (files == null || files.size() == 0) {
  141. errorCollector.print("ERROR: nothing to parse for submission \"" + name + "\"", null);
  142. tokenList = null;
  143. hasErrors = true; // invalidate submission
  144. return false;
  145. }
  146. String[] relativeFilePaths = getRelativeFilePaths(submissionRootFile, files);
  147. tokenList = language.parse(submissionRootFile, relativeFilePaths);
  148. if (!language.hasErrors()) {
  149. if (tokenList.size() < 3) {
  150. errorCollector.print("Submission \"" + name + "\" is too short!", null);
  151. tokenList = null;
  152. hasErrors = true; // invalidate submission
  153. return false;
  154. }
  155. return true;
  156. }
  157. tokenList = null;
  158. hasErrors = true; // invalidate submission
  159. if (debugParser) {
  160. copySubmission();
  161. }
  162. return false;
  163. }
  164. /**
  165. * Used by the "Report" class. All source files are returned as an array of an array of strings.
  166. */
  167. public String[][] readFiles(String[] files) throws ReportGenerationException {
  168. String[][] result = new String[files.length][];
  169. String help;
  170. List<String> text = new ArrayList<>();
  171. for (int i = 0; i < files.length; i++) {
  172. text.clear();
  173. try {
  174. FileInputStream fileInputStream = new FileInputStream(new File(submissionRootFile, files[i]));
  175. InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, JPlagOptions.CHARSET);
  176. BufferedReader in = new BufferedReader(inputStreamReader);
  177. while ((help = in.readLine()) != null) {
  178. help = help.replaceAll("&", "&amp;");
  179. help = help.replaceAll("<", "&lt;");
  180. help = help.replaceAll(">", "&gt;");
  181. help = help.replaceAll("\"", "&quot;");
  182. text.add(help);
  183. }
  184. in.close();
  185. inputStreamReader.close();
  186. fileInputStream.close();
  187. } catch (FileNotFoundException e) {
  188. System.out.println("File not found: " + new File(submissionRootFile, files[i]));
  189. } catch (IOException e) {
  190. throw new ReportGenerationException("I/O exception!", e);
  191. }
  192. result[i] = new String[text.size()];
  193. text.toArray(result[i]);
  194. }
  195. return result;
  196. }
  197. /**
  198. * Used by the "Report" class. All source files are returned as an array of an array of chars.
  199. */
  200. public char[][] readFilesChar(String[] files) throws ReportGenerationException {
  201. char[][] result = new char[files.length][];
  202. for (int i = 0; i < files.length; i++) {
  203. // If the token path is absolute, ignore the provided directory
  204. File file = new File(files[i]);
  205. if (!file.isAbsolute()) {
  206. file = new File(submissionRootFile, files[i]);
  207. }
  208. try {
  209. int size = (int) file.length();
  210. char[] buffer = new char[size];
  211. FileReader reader = new FileReader(file, JPlagOptions.CHARSET);
  212. if (size != reader.read(buffer)) {
  213. System.out.println("Not right size read from the file, but I will still continue...");
  214. }
  215. result[i] = buffer;
  216. reader.close();
  217. } catch (FileNotFoundException e) {
  218. throw new ReportGenerationException("File not found: " + file.getPath(), e);
  219. } catch (IOException e) {
  220. throw new ReportGenerationException("I/O exception reading file \"" + file.getPath() + "\"!", e);
  221. }
  222. }
  223. return result;
  224. }
  225. /**
  226. * Resets the base code flag for all tokens of this submission.
  227. */
  228. public void resetBaseCode() {
  229. for (Token token : tokenList.allTokens()) {
  230. token.setBasecode(false);
  231. }
  232. }
  233. /**
  234. * Sets the tokens that have been parsed from the files this submission consists of.
  235. * @param tokenList is the list of these tokens.
  236. */
  237. public void setTokenList(TokenList tokenList) {
  238. this.tokenList = tokenList;
  239. }
  240. public void markAsErroneous() {
  241. hasErrors = true;
  242. }
  243. @Override
  244. public int compareTo(Submission other) {
  245. return name.compareTo(other.name);
  246. }
  247. @Override
  248. public String toString() {
  249. return name;
  250. }
  251. /**
  252. * This method is used to copy files that can not be parsed to a special folder.
  253. */
  254. private void copySubmission() {
  255. File rootDirectory = submissionRootFile.getParentFile();
  256. assert rootDirectory != null;
  257. File submissionDirectory = createSubdirectory(rootDirectory, ERROR_FOLDER, language.getShortName(), name);
  258. for (File file : files) {
  259. try {
  260. Files.copy(file.toPath(), new File(submissionDirectory, file.getName()).toPath());
  261. } catch (IOException exception) {
  262. errorCollector.print("Error copying file: " + exception + "\n", null);
  263. }
  264. }
  265. }
  266. private File createSubdirectory(File parent, String... subdirectoryNames) {
  267. File subdirectory = parent;
  268. for (String name : subdirectoryNames) {
  269. subdirectory = new File(subdirectory, name);
  270. }
  271. if (!subdirectory.exists()) {
  272. subdirectory.mkdirs();
  273. }
  274. return subdirectory;
  275. }
  276. /**
  277. * Map all files of this submission to their path relative to the submission directory.
  278. * <p>
  279. * This method is required to stay compatible with `language.parse(...)` as it requires the given file paths to be
  280. * relative to the submission directory.
  281. * <p>
  282. * In a future update, `language.parse(...)` should probably just take a list of files.
  283. * @param baseFile - File to base all relative file paths on.
  284. * @param files - List of files to map.
  285. * @return an array of file paths relative to the submission directory.
  286. */
  287. private String[] getRelativeFilePaths(File baseFile, Collection<File> files) {
  288. Path baseFilePath = baseFile.toPath();
  289. return files.stream().map(File::toPath).map(baseFilePath::relativize).map(Path::toString).toArray(String[]::new);
  290. }
  291. }