Use StreamCopier from utils.
[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 (!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         public void run() {
447                 fireProjectInsertStarted();
448                 List<ScannedFile> files = fileScanner.getFiles();
449
450                 /* create connection to node */
451                 synchronized (lockObject) {
452                         connection = freenetInterface.getConnection("project-insert-" + random + counter++);
453                 }
454                 connection.setTempDirectory(tempDirectory);
455                 boolean connected = false;
456                 Throwable cause = null;
457                 try {
458                         connected = connection.connect();
459                 } catch (IOException e1) {
460                         cause = e1;
461                 }
462
463                 if (!connected || cancelled) {
464                         fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
465                         return;
466                 }
467
468                 Client client = new Client(connection);
469
470                 /* collect files */
471                 int edition = project.getEdition();
472                 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
473                 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
474                 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
475                         putDir.setDefaultName(project.getIndexFile());
476                 }
477                 putDir.setVerbosity(Verbosity.ALL);
478                 putDir.setMaxRetries(-1);
479                 putDir.setEarlyEncode(useEarlyEncode);
480                 putDir.setPriorityClass(priority);
481                 putDir.setManifestPutter(manifestPutter);
482                 for (ScannedFile file : files) {
483                         FileEntry fileEntry = createFileEntry(file, edition);
484                         if (fileEntry != null) {
485                                 try {
486                                         putDir.addFileEntry(fileEntry);
487                                 } catch (IOException ioe1) {
488                                         fireProjectInsertFinished(false, ioe1);
489                                         return;
490                                 }
491                         }
492                 }
493
494                 /* start request */
495                 try {
496                         client.execute(putDir, progressListener);
497                         fireProjectUploadFinished();
498                 } catch (IOException ioe1) {
499                         fireProjectInsertFinished(false, ioe1);
500                         return;
501                 }
502
503                 /* parse progress and success messages */
504                 String finalURI = null;
505                 boolean success = false;
506                 boolean finished = false;
507                 boolean disconnected = false;
508                 while (!finished && !cancelled) {
509                         Message message = client.readMessage();
510                         finished = (message == null) || (disconnected = client.isDisconnected());
511                         logger.log(Level.FINE, "Received message: " + message);
512                         if (!finished) {
513                                 @SuppressWarnings("null")
514                                 String messageName = message.getName();
515                                 if ("URIGenerated".equals(messageName)) {
516                                         finalURI = message.get("URI");
517                                         fireProjectURIGenerated(finalURI);
518                                 }
519                                 if ("SimpleProgress".equals(messageName)) {
520                                         int total = Integer.parseInt(message.get("Total"));
521                                         int succeeded = Integer.parseInt(message.get("Succeeded"));
522                                         int fatal = Integer.parseInt(message.get("FatallyFailed"));
523                                         int failed = Integer.parseInt(message.get("Failed"));
524                                         boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
525                                         fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
526                                 }
527                                 success |= "PutSuccessful".equals(messageName);
528                                 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
529                         }
530                 }
531
532                 /* post-insert work */
533                 if (success) {
534                         @SuppressWarnings("null")
535                         String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
536                         int newEdition = Integer.parseInt(editionPart);
537                         project.setEdition(newEdition);
538                         project.setLastInsertionTime(System.currentTimeMillis());
539                         project.onSuccessfulInsert();
540                 }
541                 fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
542         }
543
544         //
545         // INTERFACE FileScannerListener
546         //
547
548         /**
549          * {@inheritDoc}
550          */
551         public void fileScannerFinished(FileScanner fileScanner) {
552                 if (!fileScanner.isError()) {
553                         new Thread(this).start();
554                 } else {
555                         fireProjectInsertFinished(false, null);
556                 }
557                 fileScanner.removeFileScannerListener(this);
558         }
559
560         /**
561          * Container class that collects all warnings and errors that occured during
562          * {@link ProjectInserter#validateProject(Project) project validation}.
563          *
564          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
565          */
566         public static class CheckReport implements Iterable<Issue> {
567
568                 /** The issures that occured. */
569                 private final List<Issue> issues = new ArrayList<Issue>();
570
571                 /**
572                  * Adds an issue.
573                  *
574                  * @param issue
575                  *            The issue to add
576                  */
577                 public void addIssue(Issue issue) {
578                         issues.add(issue);
579                 }
580
581                 /**
582                  * Creates an {@link Issue} from the given error key and fatality flag
583                  * and {@link #addIssue(Issue) adds} it.
584                  *
585                  * @param errorKey
586                  *            The error key
587                  * @param fatal
588                  *            {@code true} if the error is fatal, {@code false} if only
589                  *            a warning should be generated
590                  * @param parameters
591                  *            Any additional parameters
592                  */
593                 public void addIssue(String errorKey, boolean fatal, String... parameters) {
594                         addIssue(new Issue(errorKey, fatal, parameters));
595                 }
596
597                 /**
598                  * {@inheritDoc}
599                  */
600                 public Iterator<Issue> iterator() {
601                         return issues.iterator();
602                 }
603
604                 /**
605                  * Returns whether this check report does not contain any errors.
606                  *
607                  * @return {@code true} if this check report does not contain any
608                  *         errors, {@code false} if this check report does contain
609                  *         errors
610                  */
611                 public boolean isEmpty() {
612                         return issues.isEmpty();
613                 }
614
615                 /**
616                  * Returns the number of issues in this check report.
617                  *
618                  * @return The number of issues
619                  */
620                 public int size() {
621                         return issues.size();
622                 }
623
624         }
625
626         /**
627          * Container class for a single issue. An issue contains an error key
628          * that describes the error, and a fatality flag that determines whether
629          * the insert has to be aborted (if the flag is {@code true}) or if it
630          * can still be performed and only a warning should be generated (if the
631          * flag is {@code false}).
632          *
633          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
634          *         Roden</a>
635          */
636         public static class Issue {
637
638                 /** The error key. */
639                 private final String errorKey;
640
641                 /** The fatality flag. */
642                 private final boolean fatal;
643
644                 /** Additional parameters. */
645                 private String[] parameters;
646
647                 /**
648                  * Creates a new issue.
649                  *
650                  * @param errorKey
651                  *            The error key
652                  * @param fatal
653                  *            The fatality flag
654                  * @param parameters
655                  *            Any additional parameters
656                  */
657                 protected Issue(String errorKey, boolean fatal, String... parameters) {
658                         this.errorKey = errorKey;
659                         this.fatal = fatal;
660                         this.parameters = parameters;
661                 }
662
663                 /**
664                  * Returns the key of the encountered error.
665                  *
666                  * @return The error key
667                  */
668                 public String getErrorKey() {
669                         return errorKey;
670                 }
671
672                 /**
673                  * Returns whether the issue is fatal and the insert has to be
674                  * aborted. Otherwise only a warning should be shown.
675                  *
676                  * @return {@code true} if the insert needs to be aborted, {@code
677                  *         false} otherwise
678                  */
679                 public boolean isFatal() {
680                         return fatal;
681                 }
682
683                 /**
684                  * Returns any additional parameters.
685                  *
686                  * @return The additional parameters
687                  */
688                 public String[] getParameters() {
689                         return parameters;
690                 }
691
692         }
693
694 }