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