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