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