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