Remove manifest putter selection
[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.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.Connection;
47 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
48 import de.todesbaum.util.freenet.fcp2.FileEntry;
49 import de.todesbaum.util.freenet.fcp2.Message;
50 import de.todesbaum.util.freenet.fcp2.PriorityClass;
51 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
52 import de.todesbaum.util.freenet.fcp2.Verbosity;
53
54 /**
55  * Manages project inserts.
56  *
57  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
58  */
59 public class ProjectInserter implements FileScannerListener, Runnable {
60
61         /** The logger. */
62         private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
63
64         /** Random number for FCP instances. */
65         private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
66
67         /** Counter for FCP connection identifier. */
68         private static int counter = 0;
69
70         private final ProjectInsertListeners projectInsertListeners = new ProjectInsertListeners();
71
72         /** The freenet interface. */
73         private Freenet7Interface freenetInterface;
74
75         /** The project to insert. */
76         private Project project;
77
78         /** The file scanner. */
79         private FileScanner fileScanner;
80
81         /** Object used for synchronization. */
82         private final Object lockObject = new Object();
83
84         /** The temp directory. */
85         private String tempDirectory;
86
87         /** The current connection. */
88         private Connection connection;
89
90         /** Whether the insert is cancelled. */
91         private volatile boolean cancelled = false;
92
93         /** Progress listener for payload transfers. */
94         private ProgressListener progressListener;
95
96         /** Whether to use “early encode.” */
97         private boolean useEarlyEncode;
98
99         /** The insert priority. */
100         private PriorityClass priority;
101
102         /**
103          * Adds a listener to the list of registered listeners.
104          *
105          * @param insertListener
106          *            The listener to add
107          */
108         public void addInsertListener(InsertListener insertListener) {
109                 projectInsertListeners.addInsertListener(insertListener);
110         }
111
112         /**
113          * Sets the project to insert.
114          *
115          * @param project
116          *            The project to insert
117          */
118         public void setProject(Project project) {
119                 this.project = project;
120         }
121
122         /**
123          * Sets the freenet interface to use.
124          *
125          * @param freenetInterface
126          *            The freenet interface to use
127          */
128         public void setFreenetInterface(Freenet7Interface freenetInterface) {
129                 this.freenetInterface = freenetInterface;
130         }
131
132         /**
133          * Sets the temp directory to use.
134          *
135          * @param tempDirectory
136          *            The temp directory to use, or {@code null} to use the system
137          *            default
138          */
139         public void setTempDirectory(String tempDirectory) {
140                 this.tempDirectory = tempDirectory;
141         }
142
143         /**
144          * Sets whether to use the “early encode“ flag for the insert.
145          *
146          * @param useEarlyEncode
147          *            {@code true} to set the “early encode” flag for the insert,
148          *            {@code false} otherwise
149          */
150         public void setUseEarlyEncode(boolean useEarlyEncode) {
151                 this.useEarlyEncode = useEarlyEncode;
152         }
153
154         /**
155          * Sets the insert priority.
156          *
157          * @param priority
158          *            The insert priority
159          */
160         public void setPriority(PriorityClass priority) {
161                 this.priority = priority;
162         }
163
164         /**
165          * Starts the insert.
166          *
167          * @param progressListener
168          *            Listener to notify on progress events
169          */
170         public void start(ProgressListener progressListener) {
171                 cancelled = false;
172                 this.progressListener = progressListener;
173                 fileScanner = new FileScanner(project);
174                 fileScanner.addFileScannerListener(this);
175                 new Thread(fileScanner).start();
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                 FileScanner fileScanner = new FileScanner(project);
291                 final CountDownLatch completionLatch = new CountDownLatch(1);
292                 fileScanner.addFileScannerListener(new FileScannerListener() {
293
294                         @Override
295                         public void fileScannerFinished(FileScanner fileScanner) {
296                                 completionLatch.countDown();
297                         }
298                 });
299                 new Thread(fileScanner).start();
300                 while (completionLatch.getCount() > 0) {
301                         try {
302                                 completionLatch.await();
303                         } catch (InterruptedException ie1) {
304                                 /* TODO: logging */
305                         }
306                 }
307                 for (ScannedFile scannedFile : fileScanner.getFiles()) {
308                         String fileName = scannedFile.getFilename();
309                         FileOption fileOption = project.getFileOption(fileName);
310                         if ((fileOption != null) && !fileOption.isInsert()) {
311                                 continue;
312                         }
313                         totalSize += new File(project.getLocalPath(), fileName).length();
314                 }
315                 if (totalSize > 2 * 1024 * 1024) {
316                         checkReport.addIssue("warning.site-larger-than-2-mib", false);
317                 }
318                 return checkReport;
319         }
320
321         /**
322          * {@inheritDoc}
323          */
324         @Override
325         public void run() {
326                 projectInsertListeners.fireProjectInsertStarted(project);
327                 List<ScannedFile> files = fileScanner.getFiles();
328
329                 /* create connection to node */
330                 synchronized (lockObject) {
331                         connection = freenetInterface.getConnection("project-insert-" + random + counter++);
332                 }
333                 connection.setTempDirectory(tempDirectory);
334                 boolean connected = false;
335                 Throwable cause = null;
336                 try {
337                         connected = connection.connect();
338                 } catch (IOException e1) {
339                         cause = e1;
340                 }
341
342                 if (!connected || cancelled) {
343                         projectInsertListeners.fireProjectInsertFinished(project, false, cancelled ? new AbortedException() : cause);
344                         return;
345                 }
346
347                 Client client = new Client(connection);
348
349                 /* collect files */
350                 int edition = project.getEdition();
351                 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
352                 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
353                 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
354                         FileOption indexFileOption = project.getFileOption(project.getIndexFile());
355                         Optional<String> changedName = indexFileOption.getChangedName();
356                         if (changedName.isPresent()) {
357                                 putDir.setDefaultName(changedName.get());
358                         } else {
359                                 putDir.setDefaultName(project.getIndexFile());
360                         }
361                 }
362                 putDir.setVerbosity(Verbosity.ALL);
363                 putDir.setMaxRetries(-1);
364                 putDir.setEarlyEncode(useEarlyEncode);
365                 putDir.setPriorityClass(priority);
366                 for (ScannedFile file : files) {
367                         FileEntry fileEntry = createFileEntry(file);
368                         if (fileEntry != null) {
369                                 try {
370                                         putDir.addFileEntry(fileEntry);
371                                 } catch (IOException ioe1) {
372                                         projectInsertListeners.fireProjectInsertFinished(project, false, ioe1);
373                                         return;
374                                 }
375                         }
376                 }
377
378                 /* start request */
379                 try {
380                         client.execute(putDir, progressListener);
381                         projectInsertListeners.fireProjectUploadFinished(project);
382                 } catch (IOException ioe1) {
383                         projectInsertListeners.fireProjectInsertFinished(project, false, ioe1);
384                         return;
385                 }
386
387                 /* parse progress and success messages */
388                 String finalURI = null;
389                 boolean success = false;
390                 boolean finished = false;
391                 boolean disconnected = false;
392                 while (!finished && !cancelled) {
393                         Message message = client.readMessage();
394                         finished = (message == null) || (disconnected = client.isDisconnected());
395                         logger.log(Level.FINE, "Received message: " + message);
396                         if (!finished) {
397                                 @SuppressWarnings("null")
398                                 String messageName = message.getName();
399                                 if ("URIGenerated".equals(messageName)) {
400                                         finalURI = message.get("URI");
401                                         projectInsertListeners.fireProjectURIGenerated(project, finalURI);
402                                 }
403                                 if ("SimpleProgress".equals(messageName)) {
404                                         int total = Integer.parseInt(message.get("Total"));
405                                         int succeeded = Integer.parseInt(message.get("Succeeded"));
406                                         int fatal = Integer.parseInt(message.get("FatallyFailed"));
407                                         int failed = Integer.parseInt(message.get("Failed"));
408                                         boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
409                                         projectInsertListeners.fireProjectInsertProgress(project, succeeded, failed, fatal, total, finalized);
410                                 }
411                                 success |= "PutSuccessful".equals(messageName);
412                                 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
413                         }
414                 }
415
416                 /* post-insert work */
417                 if (success) {
418                         @SuppressWarnings("null")
419                         String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
420                         int newEdition = Integer.parseInt(editionPart);
421                         project.setEdition(newEdition);
422                         project.setLastInsertionTime(System.currentTimeMillis());
423                         project.onSuccessfulInsert();
424                 }
425                 projectInsertListeners.fireProjectInsertFinished(project, success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
426         }
427
428         //
429         // INTERFACE FileScannerListener
430         //
431
432         /**
433          * {@inheritDoc}
434          */
435         @Override
436         public void fileScannerFinished(FileScanner fileScanner) {
437                 if (!fileScanner.isError()) {
438                         new Thread(this).start();
439                 } else {
440                         projectInsertListeners.fireProjectInsertFinished(project, false, null);
441                 }
442                 fileScanner.removeFileScannerListener(this);
443         }
444
445         /**
446          * Container class that collects all warnings and errors that occured during
447          * {@link ProjectInserter#validateProject(Project) project validation}.
448          *
449          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
450          */
451         public static class CheckReport implements Iterable<Issue> {
452
453                 /** The issures that occured. */
454                 private final List<Issue> issues = new ArrayList<Issue>();
455
456                 /**
457                  * Adds an issue.
458                  *
459                  * @param issue
460                  *            The issue to add
461                  */
462                 public void addIssue(Issue issue) {
463                         issues.add(issue);
464                 }
465
466                 /**
467                  * Creates an {@link Issue} from the given error key and fatality flag
468                  * and {@link #addIssue(Issue) adds} it.
469                  *
470                  * @param errorKey
471                  *            The error key
472                  * @param fatal
473                  *            {@code true} if the error is fatal, {@code false} if only
474                  *            a warning should be generated
475                  * @param parameters
476                  *            Any additional parameters
477                  */
478                 public void addIssue(String errorKey, boolean fatal, String... parameters) {
479                         addIssue(new Issue(errorKey, fatal, parameters));
480                 }
481
482                 /**
483                  * {@inheritDoc}
484                  */
485                 @Override
486                 public Iterator<Issue> iterator() {
487                         return issues.iterator();
488                 }
489
490                 /**
491                  * Returns whether this check report does not contain any errors.
492                  *
493                  * @return {@code true} if this check report does not contain any
494                  *         errors, {@code false} if this check report does contain
495                  *         errors
496                  */
497                 public boolean isEmpty() {
498                         return issues.isEmpty();
499                 }
500
501                 /**
502                  * Returns the number of issues in this check report.
503                  *
504                  * @return The number of issues
505                  */
506                 public int size() {
507                         return issues.size();
508                 }
509
510         }
511
512         /**
513          * Container class for a single issue. An issue contains an error key
514          * that describes the error, and a fatality flag that determines whether
515          * the insert has to be aborted (if the flag is {@code true}) or if it
516          * can still be performed and only a warning should be generated (if the
517          * flag is {@code false}).
518          *
519          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
520          *         Roden</a>
521          */
522         public static class Issue {
523
524                 /** The error key. */
525                 private final String errorKey;
526
527                 /** The fatality flag. */
528                 private final boolean fatal;
529
530                 /** Additional parameters. */
531                 private String[] parameters;
532
533                 /**
534                  * Creates a new issue.
535                  *
536                  * @param errorKey
537                  *            The error key
538                  * @param fatal
539                  *            The fatality flag
540                  * @param parameters
541                  *            Any additional parameters
542                  */
543                 protected Issue(String errorKey, boolean fatal, String... parameters) {
544                         this.errorKey = errorKey;
545                         this.fatal = fatal;
546                         this.parameters = parameters;
547                 }
548
549                 /**
550                  * Returns the key of the encountered error.
551                  *
552                  * @return The error key
553                  */
554                 public String getErrorKey() {
555                         return errorKey;
556                 }
557
558                 /**
559                  * Returns whether the issue is fatal and the insert has to be
560                  * aborted. Otherwise only a warning should be shown.
561                  *
562                  * @return {@code true} if the insert needs to be aborted, {@code
563                  *         false} otherwise
564                  */
565                 public boolean isFatal() {
566                         return fatal;
567                 }
568
569                 /**
570                  * Returns any additional parameters.
571                  *
572                  * @return The additional parameters
573                  */
574                 public String[] getParameters() {
575                         return parameters;
576                 }
577
578         }
579
580 }