Move starting file scanner in background to file scanner class
[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.HashSet;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.Set;
34 import java.util.concurrent.CountDownLatch;
35 import java.util.concurrent.atomic.AtomicInteger;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38
39 import net.pterodactylus.util.io.StreamCopier.ProgressListener;
40
41 import com.google.common.base.Optional;
42 import de.todesbaum.jsite.gui.FileScanner;
43 import de.todesbaum.jsite.gui.FileScanner.ScannedFile;
44 import de.todesbaum.jsite.gui.FileScannerListener;
45 import de.todesbaum.util.freenet.fcp2.Client;
46 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
47 import de.todesbaum.util.freenet.fcp2.Connection;
48 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
49 import de.todesbaum.util.freenet.fcp2.FileEntry;
50 import de.todesbaum.util.freenet.fcp2.Message;
51 import de.todesbaum.util.freenet.fcp2.PriorityClass;
52 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
53 import de.todesbaum.util.freenet.fcp2.Verbosity;
54
55 /**
56  * Manages project inserts.
57  *
58  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
59  */
60 public class ProjectInserter implements FileScannerListener, Runnable {
61
62         /** The logger. */
63         private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
64
65         /** Random number for FCP instances. */
66         private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
67
68         /** Counter for FCP connection identifier. */
69         private static final AtomicInteger counter = new AtomicInteger();
70
71         private final ProjectInsertListeners projectInsertListeners = new ProjectInsertListeners();
72
73         /** The freenet interface. */
74         private Freenet7Interface freenetInterface;
75
76         /** The project to insert. */
77         private Project project;
78
79         /** The file scanner. */
80         private FileScanner fileScanner;
81
82         /** Object used for synchronization. */
83         private final Object lockObject = new Object();
84
85         /** The temp directory. */
86         private String tempDirectory;
87
88         /** The current connection. */
89         private Connection connection;
90
91         /** Whether the insert is cancelled. */
92         private volatile boolean cancelled = false;
93
94         /** Progress listener for payload transfers. */
95         private ProgressListener progressListener;
96
97         /** Whether to use “early encode.” */
98         private boolean useEarlyEncode;
99
100         /** The insert priority. */
101         private PriorityClass priority;
102
103         /**
104          * Adds a listener to the list of registered listeners.
105          *
106          * @param insertListener
107          *            The listener to add
108          */
109         public void addInsertListener(InsertListener insertListener) {
110                 projectInsertListeners.addInsertListener(insertListener);
111         }
112
113         /**
114          * Sets the project to insert.
115          *
116          * @param project
117          *            The project to insert
118          */
119         public void setProject(Project project) {
120                 this.project = project;
121         }
122
123         /**
124          * Sets the freenet interface to use.
125          *
126          * @param freenetInterface
127          *            The freenet interface to use
128          */
129         public void setFreenetInterface(Freenet7Interface freenetInterface) {
130                 this.freenetInterface = freenetInterface;
131         }
132
133         /**
134          * Sets the temp directory to use.
135          *
136          * @param tempDirectory
137          *            The temp directory to use, or {@code null} to use the system
138          *            default
139          */
140         public void setTempDirectory(String tempDirectory) {
141                 this.tempDirectory = tempDirectory;
142         }
143
144         /**
145          * Sets whether to use the “early encode“ flag for the insert.
146          *
147          * @param useEarlyEncode
148          *            {@code true} to set the “early encode” flag for the insert,
149          *            {@code false} otherwise
150          */
151         public void setUseEarlyEncode(boolean useEarlyEncode) {
152                 this.useEarlyEncode = useEarlyEncode;
153         }
154
155         /**
156          * Sets the insert priority.
157          *
158          * @param priority
159          *            The insert priority
160          */
161         public void setPriority(PriorityClass priority) {
162                 this.priority = priority;
163         }
164
165         /**
166          * Starts the insert.
167          *
168          * @param progressListener
169          *            Listener to notify on progress events
170          */
171         public void start(ProgressListener progressListener) {
172                 cancelled = false;
173                 this.progressListener = progressListener;
174                 fileScanner = new FileScanner(project);
175                 fileScanner.addFileScannerListener(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 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 new RedirectFileEntry(fileOption.getChangedName().or(filename), fileOption.getMimeType(), "SSK@" + project.getRequestURI() + "/" + project.getPath() + "-" + fileOption.getLastInsertEdition() + "/" + fileOption.getLastInsertFilename());
209                         }
210                         try {
211                                 return createFileEntry(filename, fileOption.getChangedName(), fileOption.getMimeType());
212                         } catch (IOException ioe1) {
213                                 /* ignore, null is returned. */
214                         }
215                 } else {
216                         if (fileOption.isInsertRedirect()) {
217                                 return new RedirectFileEntry(fileOption.getChangedName().or(filename), fileOption.getMimeType(), fileOption.getCustomKey());
218                         }
219                 }
220                 return null;
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.or(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().or(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                 FileScanner fileScanner = new FileScanner(project);
292                 final CountDownLatch completionLatch = new CountDownLatch(1);
293                 fileScanner.addFileScannerListener(new FileScannerListener() {
294
295                         @Override
296                         public void fileScannerFinished(FileScanner fileScanner) {
297                                 completionLatch.countDown();
298                         }
299                 });
300                 fileScanner.startInBackground();
301                 while (completionLatch.getCount() > 0) {
302                         try {
303                                 completionLatch.await();
304                         } catch (InterruptedException ie1) {
305                                 /* TODO: logging */
306                         }
307                 }
308                 for (ScannedFile scannedFile : fileScanner.getFiles()) {
309                         String fileName = scannedFile.getFilename();
310                         FileOption fileOption = project.getFileOption(fileName);
311                         if ((fileOption != null) && !fileOption.isInsert()) {
312                                 continue;
313                         }
314                         totalSize += new File(project.getLocalPath(), fileName).length();
315                 }
316                 if (totalSize > 2 * 1024 * 1024) {
317                         checkReport.addIssue("warning.site-larger-than-2-mib", false);
318                 }
319                 return checkReport;
320         }
321
322         /**
323          * {@inheritDoc}
324          */
325         @Override
326         public void run() {
327                 projectInsertListeners.fireProjectInsertStarted(project);
328                 List<ScannedFile> files = fileScanner.getFiles();
329
330                 /* create connection to node */
331                 synchronized (lockObject) {
332                         connection = freenetInterface.getConnection("project-insert-" + random + counter.getAndIncrement());
333                 }
334                 connection.setTempDirectory(tempDirectory);
335                 boolean connected = false;
336                 Throwable cause = null;
337                 try {
338                         connected = connection.connect();
339                 } catch (IOException e1) {
340                         cause = e1;
341                 }
342
343                 if (!connected || cancelled) {
344                         projectInsertListeners.fireProjectInsertFinished(project, false, cancelled ? new AbortedException() : cause);
345                         return;
346                 }
347
348                 Client client = new Client(connection);
349
350                 /* collect files */
351                 int edition = project.getEdition();
352                 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
353                 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter.getAndIncrement(), dirURI, tempDirectory);
354                 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
355                         FileOption indexFileOption = project.getFileOption(project.getIndexFile());
356                         Optional<String> changedName = indexFileOption.getChangedName();
357                         if (changedName.isPresent()) {
358                                 putDir.setDefaultName(changedName.get());
359                         } else {
360                                 putDir.setDefaultName(project.getIndexFile());
361                         }
362                 }
363                 putDir.setVerbosity(Verbosity.ALL);
364                 putDir.setMaxRetries(-1);
365                 putDir.setEarlyEncode(useEarlyEncode);
366                 putDir.setPriorityClass(priority);
367                 for (ScannedFile file : files) {
368                         FileEntry fileEntry = createFileEntry(file);
369                         if (fileEntry != null) {
370                                 try {
371                                         putDir.addFileEntry(fileEntry);
372                                 } catch (IOException ioe1) {
373                                         projectInsertListeners.fireProjectInsertFinished(project, false, ioe1);
374                                         return;
375                                 }
376                         }
377                 }
378
379                 /* start request */
380                 try {
381                         client.execute(putDir, progressListener);
382                         projectInsertListeners.fireProjectUploadFinished(project);
383                 } catch (IOException ioe1) {
384                         projectInsertListeners.fireProjectInsertFinished(project, false, ioe1);
385                         return;
386                 }
387
388                 /* parse progress and success messages */
389                 String finalURI = null;
390                 boolean success = false;
391                 boolean finished = false;
392                 boolean disconnected = false;
393                 while (!finished && !cancelled) {
394                         Message message = client.readMessage();
395                         finished = (message == null) || (disconnected = client.isDisconnected());
396                         logger.log(Level.FINE, "Received message: " + message);
397                         if (!finished) {
398                                 @SuppressWarnings("null")
399                                 String messageName = message.getName();
400                                 if ("URIGenerated".equals(messageName)) {
401                                         finalURI = message.get("URI");
402                                         projectInsertListeners.fireProjectURIGenerated(project, finalURI);
403                                 }
404                                 if ("SimpleProgress".equals(messageName)) {
405                                         int total = Integer.parseInt(message.get("Total"));
406                                         int succeeded = Integer.parseInt(message.get("Succeeded"));
407                                         int fatal = Integer.parseInt(message.get("FatallyFailed"));
408                                         int failed = Integer.parseInt(message.get("Failed"));
409                                         boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
410                                         projectInsertListeners.fireProjectInsertProgress(project, succeeded, failed, fatal, total, finalized);
411                                 }
412                                 success |= "PutSuccessful".equals(messageName);
413                                 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
414                         }
415                 }
416
417                 /* post-insert work */
418                 if (success) {
419                         @SuppressWarnings("null")
420                         String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
421                         int newEdition = Integer.parseInt(editionPart);
422                         project.setEdition(newEdition);
423                         project.setLastInsertionTime(System.currentTimeMillis());
424                         project.onSuccessfulInsert();
425                 }
426                 projectInsertListeners.fireProjectInsertFinished(project, success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
427         }
428
429         //
430         // INTERFACE FileScannerListener
431         //
432
433         /**
434          * {@inheritDoc}
435          */
436         @Override
437         public void fileScannerFinished(FileScanner fileScanner) {
438                 if (!fileScanner.isError()) {
439                         new Thread(this).start();
440                 } else {
441                         projectInsertListeners.fireProjectInsertFinished(project, false, null);
442                 }
443                 fileScanner.removeFileScannerListener(this);
444         }
445
446         /**
447          * Container class that collects all warnings and errors that occured during
448          * {@link ProjectInserter#validateProject(Project) project validation}.
449          *
450          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
451          */
452         public static class CheckReport implements Iterable<Issue> {
453
454                 /** The issures that occured. */
455                 private final List<Issue> issues = new ArrayList<Issue>();
456
457                 /**
458                  * Adds an issue.
459                  *
460                  * @param issue
461                  *            The issue to add
462                  */
463                 public void addIssue(Issue issue) {
464                         issues.add(issue);
465                 }
466
467                 /**
468                  * Creates an {@link Issue} from the given error key and fatality flag
469                  * and {@link #addIssue(Issue) adds} it.
470                  *
471                  * @param errorKey
472                  *            The error key
473                  * @param fatal
474                  *            {@code true} if the error is fatal, {@code false} if only
475                  *            a warning should be generated
476                  * @param parameters
477                  *            Any additional parameters
478                  */
479                 public void addIssue(String errorKey, boolean fatal, String... parameters) {
480                         addIssue(new Issue(errorKey, fatal, parameters));
481                 }
482
483                 /**
484                  * {@inheritDoc}
485                  */
486                 @Override
487                 public Iterator<Issue> iterator() {
488                         return issues.iterator();
489                 }
490
491                 /**
492                  * Returns whether this check report does not contain any errors.
493                  *
494                  * @return {@code true} if this check report does not contain any
495                  *         errors, {@code false} if this check report does contain
496                  *         errors
497                  */
498                 public boolean isEmpty() {
499                         return issues.isEmpty();
500                 }
501
502                 /**
503                  * Returns the number of issues in this check report.
504                  *
505                  * @return The number of issues
506                  */
507                 public int size() {
508                         return issues.size();
509                 }
510
511         }
512
513         /**
514          * Container class for a single issue. An issue contains an error key
515          * that describes the error, and a fatality flag that determines whether
516          * the insert has to be aborted (if the flag is {@code true}) or if it
517          * can still be performed and only a warning should be generated (if the
518          * flag is {@code false}).
519          *
520          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
521          *         Roden</a>
522          */
523         public static class Issue {
524
525                 /** The error key. */
526                 private final String errorKey;
527
528                 /** The fatality flag. */
529                 private final boolean fatal;
530
531                 /** Additional parameters. */
532                 private String[] parameters;
533
534                 /**
535                  * Creates a new issue.
536                  *
537                  * @param errorKey
538                  *            The error key
539                  * @param fatal
540                  *            The fatality flag
541                  * @param parameters
542                  *            Any additional parameters
543                  */
544                 protected Issue(String errorKey, boolean fatal, String... parameters) {
545                         this.errorKey = errorKey;
546                         this.fatal = fatal;
547                         this.parameters = parameters;
548                 }
549
550                 /**
551                  * Returns the key of the encountered error.
552                  *
553                  * @return The error key
554                  */
555                 public String getErrorKey() {
556                         return errorKey;
557                 }
558
559                 /**
560                  * Returns whether the issue is fatal and the insert has to be
561                  * aborted. Otherwise only a warning should be shown.
562                  *
563                  * @return {@code true} if the insert needs to be aborted, {@code
564                  *         false} otherwise
565                  */
566                 public boolean isFatal() {
567                         return fatal;
568                 }
569
570                 /**
571                  * Returns any additional parameters.
572                  *
573                  * @return The additional parameters
574                  */
575                 public String[] getParameters() {
576                         return parameters;
577                 }
578
579         }
580
581 }