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