Use a project’s “always force insert” setting when inserting the project.
[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.IOException;
24 import java.io.InputStream;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Set;
33 import java.util.concurrent.CountDownLatch;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
36
37 import net.pterodactylus.util.io.StreamCopier.ProgressListener;
38 import de.todesbaum.jsite.gui.FileScanner;
39 import de.todesbaum.jsite.gui.FileScanner.ScannedFile;
40 import de.todesbaum.jsite.gui.FileScannerListener;
41 import de.todesbaum.util.freenet.fcp2.Client;
42 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
43 import de.todesbaum.util.freenet.fcp2.ClientPutDir.ManifestPutter;
44 import de.todesbaum.util.freenet.fcp2.Connection;
45 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
46 import de.todesbaum.util.freenet.fcp2.FileEntry;
47 import de.todesbaum.util.freenet.fcp2.Message;
48 import de.todesbaum.util.freenet.fcp2.PriorityClass;
49 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
50 import de.todesbaum.util.freenet.fcp2.Verbosity;
51
52 /**
53  * Manages project inserts.
54  *
55  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
56  */
57 public class ProjectInserter implements FileScannerListener, Runnable {
58
59         /** The logger. */
60         private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
61
62         /** Random number for FCP instances. */
63         private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
64
65         /** Counter for FCP connection identifier. */
66         private static int counter = 0;
67
68         /** The list of insert listeners. */
69         private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
70
71         /** The freenet interface. */
72         protected Freenet7Interface freenetInterface;
73
74         /** The project to insert. */
75         protected Project project;
76
77         /** The file scanner. */
78         private FileScanner fileScanner;
79
80         /** Object used for synchronization. */
81         protected final Object lockObject = new Object();
82
83         /** The temp directory. */
84         private String tempDirectory;
85
86         /** The current connection. */
87         private Connection connection;
88
89         /** Whether the insert is cancelled. */
90         private volatile boolean cancelled = false;
91
92         /** Progress listener for payload transfers. */
93         private ProgressListener progressListener;
94
95         /** Whether to use “early encode.” */
96         private boolean useEarlyEncode;
97
98         /** The insert priority. */
99         private PriorityClass priority;
100
101         /** The manifest putter. */
102         private ManifestPutter manifestPutter;
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                 insertListeners.add(insertListener);
112         }
113
114         /**
115          * Removes a listener from the list of registered listeners.
116          *
117          * @param insertListener
118          *            The listener to remove
119          */
120         public void removeInsertListener(InsertListener insertListener) {
121                 insertListeners.remove(insertListener);
122         }
123
124         /**
125          * Notifies all listeners that the project insert has started.
126          *
127          * @see InsertListener#projectInsertStarted(Project)
128          */
129         protected void fireProjectInsertStarted() {
130                 for (InsertListener insertListener : insertListeners) {
131                         insertListener.projectInsertStarted(project);
132                 }
133         }
134
135         /**
136          * Notifies all listeners that the insert has generated a URI.
137          *
138          * @see InsertListener#projectURIGenerated(Project, String)
139          * @param uri
140          *            The generated URI
141          */
142         protected void fireProjectURIGenerated(String uri) {
143                 for (InsertListener insertListener : insertListeners) {
144                         insertListener.projectURIGenerated(project, uri);
145                 }
146         }
147
148         /**
149          * Notifies all listeners that the insert has made some progress.
150          *
151          * @see InsertListener#projectUploadFinished(Project)
152          */
153         protected void fireProjectUploadFinished() {
154                 for (InsertListener insertListener : insertListeners) {
155                         insertListener.projectUploadFinished(project);
156                 }
157         }
158
159         /**
160          * Notifies all listeners that the insert has made some progress.
161          *
162          * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
163          *      boolean)
164          * @param succeeded
165          *            The number of succeeded blocks
166          * @param failed
167          *            The number of failed blocks
168          * @param fatal
169          *            The number of fatally failed blocks
170          * @param total
171          *            The total number of blocks
172          * @param finalized
173          *            <code>true</code> if the total number of blocks has already
174          *            been finalized, <code>false</code> otherwise
175          */
176         protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
177                 for (InsertListener insertListener : insertListeners) {
178                         insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
179                 }
180         }
181
182         /**
183          * Notifies all listeners the project insert has finished.
184          *
185          * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
186          * @param success
187          *            <code>true</code> if the project was inserted successfully,
188          *            <code>false</code> if it failed
189          * @param cause
190          *            The cause of the failure, if any
191          */
192         protected void fireProjectInsertFinished(boolean success, Throwable cause) {
193                 for (InsertListener insertListener : insertListeners) {
194                         insertListener.projectInsertFinished(project, success, cause);
195                 }
196         }
197
198         /**
199          * Sets the project to insert.
200          *
201          * @param project
202          *            The project to insert
203          */
204         public void setProject(Project project) {
205                 this.project = project;
206         }
207
208         /**
209          * Sets the freenet interface to use.
210          *
211          * @param freenetInterface
212          *            The freenet interface to use
213          */
214         public void setFreenetInterface(Freenet7Interface freenetInterface) {
215                 this.freenetInterface = freenetInterface;
216         }
217
218         /**
219          * Sets the temp directory to use.
220          *
221          * @param tempDirectory
222          *            The temp directory to use, or {@code null} to use the system
223          *            default
224          */
225         public void setTempDirectory(String tempDirectory) {
226                 this.tempDirectory = tempDirectory;
227         }
228
229         /**
230          * Sets whether to use the “early encode“ flag for the insert.
231          *
232          * @param useEarlyEncode
233          *            {@code true} to set the “early encode” flag for the insert,
234          *            {@code false} otherwise
235          */
236         public void setUseEarlyEncode(boolean useEarlyEncode) {
237                 this.useEarlyEncode = useEarlyEncode;
238         }
239
240         /**
241          * Sets the insert priority.
242          *
243          * @param priority
244          *            The insert priority
245          */
246         public void setPriority(PriorityClass priority) {
247                 this.priority = priority;
248         }
249
250         /**
251          * Sets the manifest putter to use for inserts.
252          *
253          * @param manifestPutter
254          *            The manifest putter to use
255          */
256         public void setManifestPutter(ManifestPutter manifestPutter) {
257                 this.manifestPutter = manifestPutter;
258         }
259
260         /**
261          * Starts the insert.
262          *
263          * @param progressListener
264          *            Listener to notify on progress events
265          */
266         public void start(ProgressListener progressListener) {
267                 cancelled = false;
268                 this.progressListener = progressListener;
269                 fileScanner = new FileScanner(project);
270                 fileScanner.addFileScannerListener(this);
271                 new Thread(fileScanner).start();
272         }
273
274         /**
275          * Stops the current insert.
276          */
277         public void stop() {
278                 cancelled = true;
279                 synchronized (lockObject) {
280                         if (connection != null) {
281                                 connection.disconnect();
282                         }
283                 }
284         }
285
286         /**
287          * Creates an input stream that delivers the given file, replacing edition
288          * tokens in the file’s content, if necessary.
289          *
290          * @param filename
291          *            The name of the file
292          * @param fileOption
293          *            The file options
294          * @param edition
295          *            The current edition
296          * @param length
297          *            An array containing a single long which is used to
298          *            <em>return</em> the final length of the file, after all
299          *            replacements
300          * @return The input stream for the file
301          * @throws IOException
302          *             if an I/O error occurs
303          */
304         private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
305                 File file = new File(project.getLocalPath(), filename);
306                 length[0] = file.length();
307                 return new FileInputStream(file);
308         }
309
310         /**
311          * Creates a file entry suitable for handing in to
312          * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
313          *
314          * @param file
315          *            The name and hash of the file to insert
316          * @param edition
317          *            The current edition
318          * @return A file entry for the given file
319          */
320         private FileEntry createFileEntry(ScannedFile file, int edition) {
321                 FileEntry fileEntry = null;
322                 String filename = file.getFilename();
323                 FileOption fileOption = project.getFileOption(filename);
324                 if (fileOption.isInsert()) {
325                         fileOption.setCurrentHash(file.getHash());
326                         /* check if file was modified. */
327                         if (!project.isAlwaysForceInsert() && !fileOption.isForceInsert() && file.getHash().equals(fileOption.getLastInsertHash())) {
328                                 /* only insert a redirect. */
329                                 logger.log(Level.FINE, String.format("Inserting redirect to edition %d for %s.", fileOption.getLastInsertEdition(), filename));
330                                 return new RedirectFileEntry(fileOption.hasChangedName() ? fileOption.getChangedName() : filename, fileOption.getMimeType(), "SSK@" + project.getRequestURI() + "/" + project.getPath() + "-" + fileOption.getLastInsertEdition() + "/" + fileOption.getLastInsertFilename());
331                         }
332                         try {
333                                 long[] fileLength = new long[1];
334                                 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
335                                 fileEntry = new DirectFileEntry(fileOption.hasChangedName() ? fileOption.getChangedName() : filename, fileOption.getMimeType(), fileEntryInputStream, fileLength[0]);
336                         } catch (IOException ioe1) {
337                                 /* ignore, null is returned. */
338                         }
339                 } else {
340                         if (fileOption.isInsertRedirect()) {
341                                 fileEntry = new RedirectFileEntry(fileOption.hasChangedName() ? fileOption.getChangedName() : filename, fileOption.getMimeType(), fileOption.getCustomKey());
342                         }
343                 }
344                 return fileEntry;
345         }
346
347         /**
348          * Validates the given project. The project will be checked for any invalid
349          * conditions, such as invalid insert or request keys, missing path names,
350          * missing default file, and so on.
351          *
352          * @param project
353          *            The project to check
354          * @return The encountered warnings and errors
355          */
356         public static CheckReport validateProject(Project project) {
357                 CheckReport checkReport = new CheckReport();
358                 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
359                         checkReport.addIssue("error.no-local-path", true);
360                 }
361                 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
362                         checkReport.addIssue("error.no-path", true);
363                 }
364                 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
365                         checkReport.addIssue("warning.empty-index", false);
366                 } else {
367                         File indexFile = new File(project.getLocalPath(), project.getIndexFile());
368                         if (!indexFile.exists()) {
369                                 checkReport.addIssue("error.index-missing", true);
370                         }
371                 }
372                 String indexFile = project.getIndexFile();
373                 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
374                 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
375                 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
376                         checkReport.addIssue("warning.index-not-html", false);
377                 }
378                 Map<String, FileOption> fileOptions = project.getFileOptions();
379                 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
380                 boolean insert = fileOptionEntries.isEmpty();
381                 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
382                         String fileName = fileOptionEntry.getKey();
383                         FileOption fileOption = fileOptionEntry.getValue();
384                         insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
385                         if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
386                                 checkReport.addIssue("error.index-not-inserted", true);
387                         }
388                         if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
389                                 checkReport.addIssue("error.no-custom-key", true, fileName);
390                         }
391                 }
392                 if (!insert) {
393                         checkReport.addIssue("error.no-files-to-insert", true);
394                 }
395                 Set<String> fileNames = new HashSet<String>();
396                 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
397                         FileOption fileOption = fileOptionEntry.getValue();
398                         if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
399                                 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
400                                 continue;
401                         }
402                         String fileName = fileOptionEntry.getKey();
403                         if (fileOption.hasChangedName()) {
404                                 fileName = fileOption.getChangedName();
405                         }
406                         logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
407                         if (!fileNames.add(fileName)) {
408                                 checkReport.addIssue("error.duplicate-file", true, fileName);
409                         }
410                 }
411                 long totalSize = 0;
412                 FileScanner fileScanner = new FileScanner(project);
413                 final CountDownLatch completionLatch = new CountDownLatch(1);
414                 fileScanner.addFileScannerListener(new FileScannerListener() {
415
416                         @Override
417                         public void fileScannerFinished(FileScanner fileScanner) {
418                                 completionLatch.countDown();
419                         }
420                 });
421                 new Thread(fileScanner).start();
422                 while (completionLatch.getCount() > 0) {
423                         try {
424                                 completionLatch.await();
425                         } catch (InterruptedException ie1) {
426                                 /* TODO: logging */
427                         }
428                 }
429                 for (ScannedFile scannedFile : fileScanner.getFiles()) {
430                         String fileName = scannedFile.getFilename();
431                         FileOption fileOption = project.getFileOption(fileName);
432                         if ((fileOption != null) && !fileOption.isInsert()) {
433                                 continue;
434                         }
435                         totalSize += new File(project.getLocalPath(), fileName).length();
436                 }
437                 if (totalSize > 2 * 1024 * 1024) {
438                         checkReport.addIssue("warning.site-larger-than-2-mib", false);
439                 }
440                 return checkReport;
441         }
442
443         /**
444          * {@inheritDoc}
445          */
446         @Override
447         public void run() {
448                 fireProjectInsertStarted();
449                 List<ScannedFile> files = fileScanner.getFiles();
450
451                 /* create connection to node */
452                 synchronized (lockObject) {
453                         connection = freenetInterface.getConnection("project-insert-" + random + counter++);
454                 }
455                 connection.setTempDirectory(tempDirectory);
456                 boolean connected = false;
457                 Throwable cause = null;
458                 try {
459                         connected = connection.connect();
460                 } catch (IOException e1) {
461                         cause = e1;
462                 }
463
464                 if (!connected || cancelled) {
465                         fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
466                         return;
467                 }
468
469                 Client client = new Client(connection);
470
471                 /* collect files */
472                 int edition = project.getEdition();
473                 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
474                 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
475                 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
476                         putDir.setDefaultName(project.getIndexFile());
477                 }
478                 putDir.setVerbosity(Verbosity.ALL);
479                 putDir.setMaxRetries(-1);
480                 putDir.setEarlyEncode(useEarlyEncode);
481                 putDir.setPriorityClass(priority);
482                 putDir.setManifestPutter(manifestPutter);
483                 for (ScannedFile file : files) {
484                         FileEntry fileEntry = createFileEntry(file, edition);
485                         if (fileEntry != null) {
486                                 try {
487                                         putDir.addFileEntry(fileEntry);
488                                 } catch (IOException ioe1) {
489                                         fireProjectInsertFinished(false, ioe1);
490                                         return;
491                                 }
492                         }
493                 }
494
495                 /* start request */
496                 try {
497                         client.execute(putDir, progressListener);
498                         fireProjectUploadFinished();
499                 } catch (IOException ioe1) {
500                         fireProjectInsertFinished(false, ioe1);
501                         return;
502                 }
503
504                 /* parse progress and success messages */
505                 String finalURI = null;
506                 boolean success = false;
507                 boolean finished = false;
508                 boolean disconnected = false;
509                 while (!finished && !cancelled) {
510                         Message message = client.readMessage();
511                         finished = (message == null) || (disconnected = client.isDisconnected());
512                         logger.log(Level.FINE, "Received message: " + message);
513                         if (!finished) {
514                                 @SuppressWarnings("null")
515                                 String messageName = message.getName();
516                                 if ("URIGenerated".equals(messageName)) {
517                                         finalURI = message.get("URI");
518                                         fireProjectURIGenerated(finalURI);
519                                 }
520                                 if ("SimpleProgress".equals(messageName)) {
521                                         int total = Integer.parseInt(message.get("Total"));
522                                         int succeeded = Integer.parseInt(message.get("Succeeded"));
523                                         int fatal = Integer.parseInt(message.get("FatallyFailed"));
524                                         int failed = Integer.parseInt(message.get("Failed"));
525                                         boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
526                                         fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
527                                 }
528                                 success |= "PutSuccessful".equals(messageName);
529                                 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
530                         }
531                 }
532
533                 /* post-insert work */
534                 if (success) {
535                         @SuppressWarnings("null")
536                         String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
537                         int newEdition = Integer.parseInt(editionPart);
538                         project.setEdition(newEdition);
539                         project.setLastInsertionTime(System.currentTimeMillis());
540                         project.onSuccessfulInsert();
541                 }
542                 fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
543         }
544
545         //
546         // INTERFACE FileScannerListener
547         //
548
549         /**
550          * {@inheritDoc}
551          */
552         @Override
553         public void fileScannerFinished(FileScanner fileScanner) {
554                 if (!fileScanner.isError()) {
555                         new Thread(this).start();
556                 } else {
557                         fireProjectInsertFinished(false, null);
558                 }
559                 fileScanner.removeFileScannerListener(this);
560         }
561
562         /**
563          * Container class that collects all warnings and errors that occured during
564          * {@link ProjectInserter#validateProject(Project) project validation}.
565          *
566          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
567          */
568         public static class CheckReport implements Iterable<Issue> {
569
570                 /** The issures that occured. */
571                 private final List<Issue> issues = new ArrayList<Issue>();
572
573                 /**
574                  * Adds an issue.
575                  *
576                  * @param issue
577                  *            The issue to add
578                  */
579                 public void addIssue(Issue issue) {
580                         issues.add(issue);
581                 }
582
583                 /**
584                  * Creates an {@link Issue} from the given error key and fatality flag
585                  * and {@link #addIssue(Issue) adds} it.
586                  *
587                  * @param errorKey
588                  *            The error key
589                  * @param fatal
590                  *            {@code true} if the error is fatal, {@code false} if only
591                  *            a warning should be generated
592                  * @param parameters
593                  *            Any additional parameters
594                  */
595                 public void addIssue(String errorKey, boolean fatal, String... parameters) {
596                         addIssue(new Issue(errorKey, fatal, parameters));
597                 }
598
599                 /**
600                  * {@inheritDoc}
601                  */
602                 @Override
603                 public Iterator<Issue> iterator() {
604                         return issues.iterator();
605                 }
606
607                 /**
608                  * Returns whether this check report does not contain any errors.
609                  *
610                  * @return {@code true} if this check report does not contain any
611                  *         errors, {@code false} if this check report does contain
612                  *         errors
613                  */
614                 public boolean isEmpty() {
615                         return issues.isEmpty();
616                 }
617
618                 /**
619                  * Returns the number of issues in this check report.
620                  *
621                  * @return The number of issues
622                  */
623                 public int size() {
624                         return issues.size();
625                 }
626
627         }
628
629         /**
630          * Container class for a single issue. An issue contains an error key
631          * that describes the error, and a fatality flag that determines whether
632          * the insert has to be aborted (if the flag is {@code true}) or if it
633          * can still be performed and only a warning should be generated (if the
634          * flag is {@code false}).
635          *
636          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
637          *         Roden</a>
638          */
639         public static class Issue {
640
641                 /** The error key. */
642                 private final String errorKey;
643
644                 /** The fatality flag. */
645                 private final boolean fatal;
646
647                 /** Additional parameters. */
648                 private String[] parameters;
649
650                 /**
651                  * Creates a new issue.
652                  *
653                  * @param errorKey
654                  *            The error key
655                  * @param fatal
656                  *            The fatality flag
657                  * @param parameters
658                  *            Any additional parameters
659                  */
660                 protected Issue(String errorKey, boolean fatal, String... parameters) {
661                         this.errorKey = errorKey;
662                         this.fatal = fatal;
663                         this.parameters = parameters;
664                 }
665
666                 /**
667                  * Returns the key of the encountered error.
668                  *
669                  * @return The error key
670                  */
671                 public String getErrorKey() {
672                         return errorKey;
673                 }
674
675                 /**
676                  * Returns whether the issue is fatal and the insert has to be
677                  * aborted. Otherwise only a warning should be shown.
678                  *
679                  * @return {@code true} if the insert needs to be aborted, {@code
680                  *         false} otherwise
681                  */
682                 public boolean isFatal() {
683                         return fatal;
684                 }
685
686                 /**
687                  * Returns any additional parameters.
688                  *
689                  * @return The additional parameters
690                  */
691                 public String[] getParameters() {
692                         return parameters;
693                 }
694
695         }
696
697 }