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