Refactor file scanner listener interface
[jSite.git] / src / main / java / de / todesbaum / jsite / application / ProjectInserter.java
1 /*
2  * jSite - ProjectInserter.java - Copyright © 2006–2014 David Roden
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */
18
19 package de.todesbaum.jsite.application;
20
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.HashSet;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Optional;
35 import java.util.Set;
36 import java.util.concurrent.CountDownLatch;
37 import java.util.concurrent.atomic.AtomicInteger;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
40
41 import net.pterodactylus.util.io.StreamCopier.ProgressListener;
42
43 import de.todesbaum.jsite.gui.FileScanner;
44 import de.todesbaum.jsite.gui.ScannedFile;
45 import de.todesbaum.jsite.gui.FileScannerListener;
46 import de.todesbaum.util.freenet.fcp2.Client;
47 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
48 import de.todesbaum.util.freenet.fcp2.Connection;
49 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
50 import de.todesbaum.util.freenet.fcp2.FileEntry;
51 import de.todesbaum.util.freenet.fcp2.Message;
52 import de.todesbaum.util.freenet.fcp2.PriorityClass;
53 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
54 import de.todesbaum.util.freenet.fcp2.Verbosity;
55
56 /**
57  * Manages project inserts.
58  *
59  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
60  */
61 public class ProjectInserter implements FileScannerListener, Runnable {
62
63         /** The logger. */
64         private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
65
66         /** Random number for FCP instances. */
67         private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
68
69         /** Counter for FCP connection identifier. */
70         private static final AtomicInteger counter = new AtomicInteger();
71
72         private final ProjectInsertListeners projectInsertListeners = new ProjectInsertListeners();
73
74         /** The freenet interface. */
75         private Freenet7Interface freenetInterface;
76
77         /** The project to insert. */
78         private Project project;
79
80         /** The file scanner. */
81         private FileScanner fileScanner;
82
83         /** Object used for synchronization. */
84         private final Object lockObject = new Object();
85
86         /** The temp directory. */
87         private String tempDirectory;
88
89         /** The current connection. */
90         private Connection connection;
91
92         /** Whether the insert is cancelled. */
93         private volatile boolean cancelled = false;
94
95         /** Progress listener for payload transfers. */
96         private ProgressListener progressListener;
97
98         /** Whether to use “early encode.” */
99         private boolean useEarlyEncode;
100
101         /** The insert priority. */
102         private PriorityClass priority;
103
104         /**
105          * Adds a listener to the list of registered listeners.
106          *
107          * @param insertListener
108          *            The listener to add
109          */
110         public void addInsertListener(InsertListener insertListener) {
111                 projectInsertListeners.addInsertListener(insertListener);
112         }
113
114         /**
115          * Sets the project to insert.
116          *
117          * @param project
118          *            The project to insert
119          */
120         public void setProject(Project project) {
121                 this.project = project;
122         }
123
124         /**
125          * Sets the freenet interface to use.
126          *
127          * @param freenetInterface
128          *            The freenet interface to use
129          */
130         public void setFreenetInterface(Freenet7Interface freenetInterface) {
131                 this.freenetInterface = freenetInterface;
132         }
133
134         /**
135          * Sets the temp directory to use.
136          *
137          * @param tempDirectory
138          *            The temp directory to use, or {@code null} to use the system
139          *            default
140          */
141         public void setTempDirectory(String tempDirectory) {
142                 this.tempDirectory = tempDirectory;
143         }
144
145         /**
146          * Sets whether to use the “early encode“ flag for the insert.
147          *
148          * @param useEarlyEncode
149          *            {@code true} to set the “early encode” flag for the insert,
150          *            {@code false} otherwise
151          */
152         public void setUseEarlyEncode(boolean useEarlyEncode) {
153                 this.useEarlyEncode = useEarlyEncode;
154         }
155
156         /**
157          * Sets the insert priority.
158          *
159          * @param priority
160          *            The insert priority
161          */
162         public void setPriority(PriorityClass priority) {
163                 this.priority = priority;
164         }
165
166         /**
167          * Starts the insert.
168          *
169          * @param progressListener
170          *            Listener to notify on progress events
171          */
172         public void start(ProgressListener progressListener) {
173                 cancelled = false;
174                 this.progressListener = progressListener;
175                 fileScanner = new FileScanner(project, this);
176                 fileScanner.startInBackground();
177         }
178
179         /**
180          * Stops the current insert.
181          */
182         public void stop() {
183                 cancelled = true;
184                 synchronized (lockObject) {
185                         if (connection != null) {
186                                 connection.disconnect();
187                         }
188                 }
189         }
190
191         /**
192          * Creates a file entry suitable for handing in to
193          * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
194          *
195          * @param file
196          *              The name and hash of the file to insert
197          * @return A file entry for the given file
198          */
199         private Optional<FileEntry> createFileEntry(ScannedFile file) {
200                 String filename = file.getFilename();
201                 FileOption fileOption = project.getFileOption(filename);
202                 if (fileOption.isInsert()) {
203                         fileOption.setCurrentHash(file.getHash());
204                         /* check if file was modified. */
205                         if (!project.isAlwaysForceInsert() && !fileOption.isForceInsert() && file.getHash().equals(fileOption.getLastInsertHash())) {
206                                 /* only insert a redirect. */
207                                 logger.log(Level.FINE, String.format("Inserting redirect to edition %d for %s.", fileOption.getLastInsertEdition(), filename));
208                                 return Optional.of(new RedirectFileEntry(fileOption.getChangedName().orElse(filename), fileOption.getMimeType(), "SSK@" + project.getRequestURI() + "/" + project.getPath() + "-" + fileOption.getLastInsertEdition() + "/" + fileOption.getLastInsertFilename()));
209                         }
210                         try {
211                                 return Optional.of(createFileEntry(filename, fileOption.getChangedName(), fileOption.getMimeType()));
212                         } catch (IOException ioe1) {
213                                 /* ignore, null is returned. */
214                         }
215                 } else {
216                         if (fileOption.isInsertRedirect()) {
217                                 return Optional.of(new RedirectFileEntry(fileOption.getChangedName().orElse(filename), fileOption.getMimeType(), fileOption.getCustomKey()));
218                         }
219                 }
220                 return Optional.empty();
221         }
222
223         private FileEntry createFileEntry(String filename, Optional<String> changedName, String mimeType) throws FileNotFoundException {
224                 File physicalFile = new File(project.getLocalPath(), filename);
225                 InputStream fileEntryInputStream = new FileInputStream(physicalFile);
226                 return new DirectFileEntry(changedName.orElse(filename), mimeType, fileEntryInputStream, physicalFile.length());
227         }
228
229         /**
230          * Validates the given project. The project will be checked for any invalid
231          * conditions, such as invalid insert or request keys, missing path names,
232          * missing default file, and so on.
233          *
234          * @param project
235          *            The project to check
236          * @return The encountered warnings and errors
237          */
238         public static CheckReport validateProject(Project project) {
239                 CheckReport checkReport = new CheckReport();
240                 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
241                         checkReport.addIssue("error.no-local-path", true);
242                 }
243                 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
244                         checkReport.addIssue("error.no-path", true);
245                 }
246                 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
247                         checkReport.addIssue("warning.empty-index", false);
248                 } else {
249                         File indexFile = new File(project.getLocalPath(), project.getIndexFile());
250                         if (!indexFile.exists()) {
251                                 checkReport.addIssue("error.index-missing", true);
252                         }
253                 }
254                 String indexFile = project.getIndexFile();
255                 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
256                 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
257                 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
258                         checkReport.addIssue("warning.index-not-html", false);
259                 }
260                 Map<String, FileOption> fileOptions = project.getFileOptions();
261                 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
262                 boolean insert = fileOptionEntries.isEmpty();
263                 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
264                         String fileName = fileOptionEntry.getKey();
265                         FileOption fileOption = fileOptionEntry.getValue();
266                         insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
267                         if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
268                                 checkReport.addIssue("error.index-not-inserted", true);
269                         }
270                         if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
271                                 checkReport.addIssue("error.no-custom-key", true, fileName);
272                         }
273                 }
274                 if (!insert) {
275                         checkReport.addIssue("error.no-files-to-insert", true);
276                 }
277                 Set<String> fileNames = new HashSet<String>();
278                 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
279                         FileOption fileOption = fileOptionEntry.getValue();
280                         if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
281                                 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
282                                 continue;
283                         }
284                         String fileName = fileOption.getChangedName().orElse(fileOptionEntry.getKey());
285                         logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
286                         if (!fileNames.add(fileName)) {
287                                 checkReport.addIssue("error.duplicate-file", true, fileName);
288                         }
289                 }
290                 long totalSize = 0;
291                 final CountDownLatch completionLatch = new CountDownLatch(1);
292                 FileScanner fileScanner = new FileScanner(project, (error, files) -> completionLatch.countDown());
293                 fileScanner.startInBackground();
294                 while (completionLatch.getCount() > 0) {
295                         try {
296                                 completionLatch.await();
297                         } catch (InterruptedException ie1) {
298                                 /* TODO: logging */
299                         }
300                 }
301                 for (ScannedFile scannedFile : fileScanner.getFiles()) {
302                         String fileName = scannedFile.getFilename();
303                         FileOption fileOption = project.getFileOption(fileName);
304                         if ((fileOption != null) && !fileOption.isInsert()) {
305                                 continue;
306                         }
307                         totalSize += new File(project.getLocalPath(), fileName).length();
308                 }
309                 if (totalSize > 2 * 1024 * 1024) {
310                         checkReport.addIssue("warning.site-larger-than-2-mib", false);
311                 }
312                 return checkReport;
313         }
314
315         /**
316          * {@inheritDoc}
317          */
318         @Override
319         public void run() {
320                 projectInsertListeners.fireProjectInsertStarted(project);
321                 List<ScannedFile> files = fileScanner.getFiles();
322
323                 /* create connection to node */
324                 synchronized (lockObject) {
325                         connection = freenetInterface.getConnection("project-insert-" + random + counter.getAndIncrement());
326                 }
327                 connection.setTempDirectory(tempDirectory);
328                 boolean connected = false;
329                 Throwable cause = null;
330                 try {
331                         connected = connection.connect();
332                 } catch (IOException e1) {
333                         cause = e1;
334                 }
335
336                 if (!connected || cancelled) {
337                         projectInsertListeners.fireProjectInsertFinished(project, false, cancelled ? new AbortedException() : cause);
338                         return;
339                 }
340
341                 Client client = new Client(connection);
342
343                 /* collect files */
344                 int edition = project.getEdition();
345                 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
346                 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter.getAndIncrement(), dirURI, tempDirectory);
347                 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
348                         FileOption indexFileOption = project.getFileOption(project.getIndexFile());
349                         Optional<String> changedName = indexFileOption.getChangedName();
350                         if (changedName.isPresent()) {
351                                 putDir.setDefaultName(changedName.get());
352                         } else {
353                                 putDir.setDefaultName(project.getIndexFile());
354                         }
355                 }
356                 putDir.setVerbosity(Verbosity.ALL);
357                 putDir.setMaxRetries(-1);
358                 putDir.setEarlyEncode(useEarlyEncode);
359                 putDir.setPriorityClass(priority);
360                 for (ScannedFile file : files) {
361                         Optional<FileEntry> fileEntry = createFileEntry(file);
362                         if (fileEntry.isPresent()) {
363                                 try {
364                                         putDir.addFileEntry(fileEntry.get());
365                                 } catch (IOException ioe1) {
366                                         projectInsertListeners.fireProjectInsertFinished(project, false, ioe1);
367                                         return;
368                                 }
369                         }
370                 }
371
372                 /* start request */
373                 try {
374                         client.execute(putDir, progressListener);
375                         projectInsertListeners.fireProjectUploadFinished(project);
376                 } catch (IOException ioe1) {
377                         projectInsertListeners.fireProjectInsertFinished(project, false, ioe1);
378                         return;
379                 }
380
381                 /* parse progress and success messages */
382                 String finalURI = null;
383                 boolean success = false;
384                 boolean finished = false;
385                 boolean disconnected = false;
386                 while (!finished && !cancelled) {
387                         Message message = client.readMessage();
388                         finished = (message == null) || (disconnected = client.isDisconnected());
389                         logger.log(Level.FINE, "Received message: " + message);
390                         if (!finished) {
391                                 @SuppressWarnings("null")
392                                 String messageName = message.getName();
393                                 if ("URIGenerated".equals(messageName)) {
394                                         finalURI = message.get("URI");
395                                         projectInsertListeners.fireProjectURIGenerated(project, finalURI);
396                                 }
397                                 if ("SimpleProgress".equals(messageName)) {
398                                         int total = Integer.parseInt(message.get("Total"));
399                                         int succeeded = Integer.parseInt(message.get("Succeeded"));
400                                         int fatal = Integer.parseInt(message.get("FatallyFailed"));
401                                         int failed = Integer.parseInt(message.get("Failed"));
402                                         boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
403                                         projectInsertListeners.fireProjectInsertProgress(project, succeeded, failed, fatal, total, finalized);
404                                 }
405                                 success |= "PutSuccessful".equals(messageName);
406                                 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
407                         }
408                 }
409
410                 /* post-insert work */
411                 if (success) {
412                         @SuppressWarnings("null")
413                         String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
414                         int newEdition = Integer.parseInt(editionPart);
415                         project.setEdition(newEdition);
416                         project.setLastInsertionTime(System.currentTimeMillis());
417                         project.onSuccessfulInsert();
418                 }
419                 projectInsertListeners.fireProjectInsertFinished(project, success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
420         }
421
422         //
423         // INTERFACE FileScannerListener
424         //
425
426         /**
427          * {@inheritDoc}
428          */
429         @Override
430         public void fileScannerFinished(boolean error, Collection<ScannedFile> files) {
431                 if (!error) {
432                         new Thread(this).start();
433                 } else {
434                         projectInsertListeners.fireProjectInsertFinished(project, false, null);
435                 }
436         }
437
438         /**
439          * Container class that collects all warnings and errors that occured during
440          * {@link ProjectInserter#validateProject(Project) project validation}.
441          *
442          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
443          */
444         public static class CheckReport implements Iterable<Issue> {
445
446                 /** The issures that occured. */
447                 private final List<Issue> issues = new ArrayList<Issue>();
448
449                 /**
450                  * Adds an issue.
451                  *
452                  * @param issue
453                  *            The issue to add
454                  */
455                 public void addIssue(Issue issue) {
456                         issues.add(issue);
457                 }
458
459                 /**
460                  * Creates an {@link Issue} from the given error key and fatality flag
461                  * and {@link #addIssue(Issue) adds} it.
462                  *
463                  * @param errorKey
464                  *            The error key
465                  * @param fatal
466                  *            {@code true} if the error is fatal, {@code false} if only
467                  *            a warning should be generated
468                  * @param parameters
469                  *            Any additional parameters
470                  */
471                 public void addIssue(String errorKey, boolean fatal, String... parameters) {
472                         addIssue(new Issue(errorKey, fatal, parameters));
473                 }
474
475                 /**
476                  * {@inheritDoc}
477                  */
478                 @Override
479                 public Iterator<Issue> iterator() {
480                         return issues.iterator();
481                 }
482
483                 /**
484                  * Returns whether this check report does not contain any errors.
485                  *
486                  * @return {@code true} if this check report does not contain any
487                  *         errors, {@code false} if this check report does contain
488                  *         errors
489                  */
490                 public boolean isEmpty() {
491                         return issues.isEmpty();
492                 }
493
494                 /**
495                  * Returns the number of issues in this check report.
496                  *
497                  * @return The number of issues
498                  */
499                 public int size() {
500                         return issues.size();
501                 }
502
503         }
504
505         /**
506          * Container class for a single issue. An issue contains an error key
507          * that describes the error, and a fatality flag that determines whether
508          * the insert has to be aborted (if the flag is {@code true}) or if it
509          * can still be performed and only a warning should be generated (if the
510          * flag is {@code false}).
511          *
512          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
513          *         Roden</a>
514          */
515         public static class Issue {
516
517                 /** The error key. */
518                 private final String errorKey;
519
520                 /** The fatality flag. */
521                 private final boolean fatal;
522
523                 /** Additional parameters. */
524                 private String[] parameters;
525
526                 /**
527                  * Creates a new issue.
528                  *
529                  * @param errorKey
530                  *            The error key
531                  * @param fatal
532                  *            The fatality flag
533                  * @param parameters
534                  *            Any additional parameters
535                  */
536                 protected Issue(String errorKey, boolean fatal, String... parameters) {
537                         this.errorKey = errorKey;
538                         this.fatal = fatal;
539                         this.parameters = parameters;
540                 }
541
542                 /**
543                  * Returns the key of the encountered error.
544                  *
545                  * @return The error key
546                  */
547                 public String getErrorKey() {
548                         return errorKey;
549                 }
550
551                 /**
552                  * Returns whether the issue is fatal and the insert has to be
553                  * aborted. Otherwise only a warning should be shown.
554                  *
555                  * @return {@code true} if the insert needs to be aborted, {@code
556                  *         false} otherwise
557                  */
558                 public boolean isFatal() {
559                         return fatal;
560                 }
561
562                 /**
563                  * Returns any additional parameters.
564                  *
565                  * @return The additional parameters
566                  */
567                 public String[] getParameters() {
568                         return parameters;
569                 }
570
571         }
572
573 }