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