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