2 * jSite - ProjectInserter.java - Copyright Ā© 2006ā2012 David Roden
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.
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.
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.
19 package de.todesbaum.jsite.application;
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;
31 import java.util.Map.Entry;
33 import java.util.concurrent.CountDownLatch;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
37 import net.pterodactylus.util.io.StreamCopier.ProgressListener;
38 import de.todesbaum.jsite.gui.FileScanner;
39 import de.todesbaum.jsite.gui.FileScanner.ScannedFile;
40 import de.todesbaum.jsite.gui.FileScannerListener;
41 import de.todesbaum.util.freenet.fcp2.Client;
42 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
43 import de.todesbaum.util.freenet.fcp2.ClientPutDir.ManifestPutter;
44 import de.todesbaum.util.freenet.fcp2.Connection;
45 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
46 import de.todesbaum.util.freenet.fcp2.FileEntry;
47 import de.todesbaum.util.freenet.fcp2.Message;
48 import de.todesbaum.util.freenet.fcp2.PriorityClass;
49 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
50 import de.todesbaum.util.freenet.fcp2.Verbosity;
53 * Manages project inserts.
55 * @author David āBombeā Roden <bombe@freenetproject.org>
57 public class ProjectInserter implements FileScannerListener, Runnable {
60 private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
62 /** Random number for FCP instances. */
63 private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
65 /** Counter for FCP connection identifier. */
66 private static int counter = 0;
68 /** The list of insert listeners. */
69 private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
71 /** The freenet interface. */
72 protected Freenet7Interface freenetInterface;
74 /** The project to insert. */
75 protected Project project;
77 /** The file scanner. */
78 private FileScanner fileScanner;
80 /** Object used for synchronization. */
81 protected final Object lockObject = new Object();
83 /** The temp directory. */
84 private String tempDirectory;
86 /** The current connection. */
87 private Connection connection;
89 /** Whether the insert is cancelled. */
90 private volatile boolean cancelled = false;
92 /** Progress listener for payload transfers. */
93 private ProgressListener progressListener;
95 /** Whether to use āearly encode.ā */
96 private boolean useEarlyEncode;
98 /** The insert priority. */
99 private PriorityClass priority;
101 /** The manifest putter. */
102 private ManifestPutter manifestPutter;
105 * Adds a listener to the list of registered listeners.
107 * @param insertListener
108 * The listener to add
110 public void addInsertListener(InsertListener insertListener) {
111 insertListeners.add(insertListener);
115 * Removes a listener from the list of registered listeners.
117 * @param insertListener
118 * The listener to remove
120 public void removeInsertListener(InsertListener insertListener) {
121 insertListeners.remove(insertListener);
125 * Notifies all listeners that the project insert has started.
127 * @see InsertListener#projectInsertStarted(Project)
129 protected void fireProjectInsertStarted() {
130 for (InsertListener insertListener : insertListeners) {
131 insertListener.projectInsertStarted(project);
136 * Notifies all listeners that the insert has generated a URI.
138 * @see InsertListener#projectURIGenerated(Project, String)
142 protected void fireProjectURIGenerated(String uri) {
143 for (InsertListener insertListener : insertListeners) {
144 insertListener.projectURIGenerated(project, uri);
149 * Notifies all listeners that the insert has made some progress.
151 * @see InsertListener#projectUploadFinished(Project)
153 protected void fireProjectUploadFinished() {
154 for (InsertListener insertListener : insertListeners) {
155 insertListener.projectUploadFinished(project);
160 * Notifies all listeners that the insert has made some progress.
162 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
165 * The number of succeeded blocks
167 * The number of failed blocks
169 * The number of fatally failed blocks
171 * The total number of blocks
173 * <code>true</code> if the total number of blocks has already
174 * been finalized, <code>false</code> otherwise
176 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
177 for (InsertListener insertListener : insertListeners) {
178 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
183 * Notifies all listeners the project insert has finished.
185 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
187 * <code>true</code> if the project was inserted successfully,
188 * <code>false</code> if it failed
190 * The cause of the failure, if any
192 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
193 for (InsertListener insertListener : insertListeners) {
194 insertListener.projectInsertFinished(project, success, cause);
199 * Sets the project to insert.
202 * The project to insert
204 public void setProject(Project project) {
205 this.project = project;
209 * Sets the freenet interface to use.
211 * @param freenetInterface
212 * The freenet interface to use
214 public void setFreenetInterface(Freenet7Interface freenetInterface) {
215 this.freenetInterface = freenetInterface;
219 * Sets the temp directory to use.
221 * @param tempDirectory
222 * The temp directory to use, or {@code null} to use the system
225 public void setTempDirectory(String tempDirectory) {
226 this.tempDirectory = tempDirectory;
230 * Sets whether to use the āearly encodeā flag for the insert.
232 * @param useEarlyEncode
233 * {@code true} to set the āearly encodeā flag for the insert,
234 * {@code false} otherwise
236 public void setUseEarlyEncode(boolean useEarlyEncode) {
237 this.useEarlyEncode = useEarlyEncode;
241 * Sets the insert priority.
244 * The insert priority
246 public void setPriority(PriorityClass priority) {
247 this.priority = priority;
251 * Sets the manifest putter to use for inserts.
253 * @param manifestPutter
254 * The manifest putter to use
256 public void setManifestPutter(ManifestPutter manifestPutter) {
257 this.manifestPutter = manifestPutter;
263 * @param progressListener
264 * Listener to notify on progress events
266 public void start(ProgressListener progressListener) {
268 this.progressListener = progressListener;
269 fileScanner = new FileScanner(project);
270 fileScanner.addFileScannerListener(this);
271 new Thread(fileScanner).start();
275 * Stops the current insert.
279 synchronized (lockObject) {
280 if (connection != null) {
281 connection.disconnect();
287 * Creates an input stream that delivers the given file, replacing edition
288 * tokens in the fileās content, if necessary.
291 * The name of the file
295 * The current edition
297 * An array containing a single long which is used to
298 * <em>return</em> the final length of the file, after all
300 * @return The input stream for the file
301 * @throws IOException
302 * if an I/O error occurs
304 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
305 File file = new File(project.getLocalPath(), filename);
306 length[0] = file.length();
307 return new FileInputStream(file);
311 * Creates a file entry suitable for handing in to
312 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
315 * The name and hash of the file to insert
317 * The current edition
318 * @return A file entry for the given file
320 private FileEntry createFileEntry(ScannedFile file, int edition) {
321 FileEntry fileEntry = null;
322 String filename = file.getFilename();
323 FileOption fileOption = project.getFileOption(filename);
324 if (fileOption.isInsert()) {
325 fileOption.setCurrentHash(file.getHash());
326 /* check if file was modified. */
327 if (!fileOption.isForceInsert() && file.getHash().equals(fileOption.getLastInsertHash())) {
328 /* only insert a redirect. */
329 logger.log(Level.FINE, String.format("Inserting redirect to edition %d for %s.", fileOption.getLastInsertEdition(), filename));
330 return new RedirectFileEntry(fileOption.hasChangedName() ? fileOption.getChangedName() : filename, fileOption.getMimeType(), "SSK@" + project.getRequestURI() + "/" + project.getPath() + "-" + fileOption.getLastInsertEdition() + "/" + fileOption.getLastInsertFilename());
333 long[] fileLength = new long[1];
334 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
335 fileEntry = new DirectFileEntry(fileOption.hasChangedName() ? fileOption.getChangedName() : filename, fileOption.getMimeType(), fileEntryInputStream, fileLength[0]);
336 } catch (IOException ioe1) {
337 /* ignore, null is returned. */
340 if (fileOption.isInsertRedirect()) {
341 fileEntry = new RedirectFileEntry(fileOption.hasChangedName() ? fileOption.getChangedName() : filename, fileOption.getMimeType(), fileOption.getCustomKey());
348 * Validates the given project. The project will be checked for any invalid
349 * conditions, such as invalid insert or request keys, missing path names,
350 * missing default file, and so on.
353 * The project to check
354 * @return The encountered warnings and errors
356 public static CheckReport validateProject(Project project) {
357 CheckReport checkReport = new CheckReport();
358 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
359 checkReport.addIssue("error.no-local-path", true);
361 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
362 checkReport.addIssue("error.no-path", true);
364 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
365 checkReport.addIssue("warning.empty-index", false);
367 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
368 if (!indexFile.exists()) {
369 checkReport.addIssue("error.index-missing", true);
372 String indexFile = project.getIndexFile();
373 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
374 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
375 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
376 checkReport.addIssue("warning.index-not-html", false);
378 Map<String, FileOption> fileOptions = project.getFileOptions();
379 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
380 boolean insert = fileOptionEntries.isEmpty();
381 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
382 String fileName = fileOptionEntry.getKey();
383 FileOption fileOption = fileOptionEntry.getValue();
384 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
385 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
386 checkReport.addIssue("error.index-not-inserted", true);
388 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
389 checkReport.addIssue("error.no-custom-key", true, fileName);
393 checkReport.addIssue("error.no-files-to-insert", true);
395 Set<String> fileNames = new HashSet<String>();
396 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
397 FileOption fileOption = fileOptionEntry.getValue();
398 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
399 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
402 String fileName = fileOptionEntry.getKey();
403 if (fileOption.hasChangedName()) {
404 fileName = fileOption.getChangedName();
406 logger.log(Level.FINEST, "Adding ā{0}ā for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
407 if (!fileNames.add(fileName)) {
408 checkReport.addIssue("error.duplicate-file", true, fileName);
412 FileScanner fileScanner = new FileScanner(project);
413 final CountDownLatch completionLatch = new CountDownLatch(1);
414 fileScanner.addFileScannerListener(new FileScannerListener() {
417 public void fileScannerFinished(FileScanner fileScanner) {
418 completionLatch.countDown();
421 new Thread(fileScanner).start();
422 while (completionLatch.getCount() > 0) {
424 completionLatch.await();
425 } catch (InterruptedException ie1) {
429 for (ScannedFile scannedFile : fileScanner.getFiles()) {
430 String fileName = scannedFile.getFilename();
431 FileOption fileOption = project.getFileOption(fileName);
432 if ((fileOption != null) && !fileOption.isInsert()) {
435 totalSize += new File(project.getLocalPath(), fileName).length();
437 if (totalSize > 2 * 1024 * 1024) {
438 checkReport.addIssue("warning.site-larger-than-2-mib", false);
448 fireProjectInsertStarted();
449 List<ScannedFile> files = fileScanner.getFiles();
451 /* create connection to node */
452 synchronized (lockObject) {
453 connection = freenetInterface.getConnection("project-insert-" + random + counter++);
455 connection.setTempDirectory(tempDirectory);
456 boolean connected = false;
457 Throwable cause = null;
459 connected = connection.connect();
460 } catch (IOException e1) {
464 if (!connected || cancelled) {
465 fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
469 Client client = new Client(connection);
472 int edition = project.getEdition();
473 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
474 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
475 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
476 putDir.setDefaultName(project.getIndexFile());
478 putDir.setVerbosity(Verbosity.ALL);
479 putDir.setMaxRetries(-1);
480 putDir.setEarlyEncode(useEarlyEncode);
481 putDir.setPriorityClass(priority);
482 putDir.setManifestPutter(manifestPutter);
483 for (ScannedFile file : files) {
484 FileEntry fileEntry = createFileEntry(file, edition);
485 if (fileEntry != null) {
487 putDir.addFileEntry(fileEntry);
488 } catch (IOException ioe1) {
489 fireProjectInsertFinished(false, ioe1);
497 client.execute(putDir, progressListener);
498 fireProjectUploadFinished();
499 } catch (IOException ioe1) {
500 fireProjectInsertFinished(false, ioe1);
504 /* parse progress and success messages */
505 String finalURI = null;
506 boolean success = false;
507 boolean finished = false;
508 boolean disconnected = false;
509 while (!finished && !cancelled) {
510 Message message = client.readMessage();
511 finished = (message == null) || (disconnected = client.isDisconnected());
512 logger.log(Level.FINE, "Received message: " + message);
514 @SuppressWarnings("null")
515 String messageName = message.getName();
516 if ("URIGenerated".equals(messageName)) {
517 finalURI = message.get("URI");
518 fireProjectURIGenerated(finalURI);
520 if ("SimpleProgress".equals(messageName)) {
521 int total = Integer.parseInt(message.get("Total"));
522 int succeeded = Integer.parseInt(message.get("Succeeded"));
523 int fatal = Integer.parseInt(message.get("FatallyFailed"));
524 int failed = Integer.parseInt(message.get("Failed"));
525 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
526 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
528 success |= "PutSuccessful".equals(messageName);
529 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
533 /* post-insert work */
535 @SuppressWarnings("null")
536 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
537 int newEdition = Integer.parseInt(editionPart);
538 project.setEdition(newEdition);
539 project.setLastInsertionTime(System.currentTimeMillis());
540 project.onSuccessfulInsert();
542 fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
546 // INTERFACE FileScannerListener
553 public void fileScannerFinished(FileScanner fileScanner) {
554 if (!fileScanner.isError()) {
555 new Thread(this).start();
557 fireProjectInsertFinished(false, null);
559 fileScanner.removeFileScannerListener(this);
563 * Container class that collects all warnings and errors that occured during
564 * {@link ProjectInserter#validateProject(Project) project validation}.
566 * @author <a href="mailto:bombe@pterodactylus.net">David āBombeā Roden</a>
568 public static class CheckReport implements Iterable<Issue> {
570 /** The issures that occured. */
571 private final List<Issue> issues = new ArrayList<Issue>();
579 public void addIssue(Issue issue) {
584 * Creates an {@link Issue} from the given error key and fatality flag
585 * and {@link #addIssue(Issue) adds} it.
590 * {@code true} if the error is fatal, {@code false} if only
591 * a warning should be generated
593 * Any additional parameters
595 public void addIssue(String errorKey, boolean fatal, String... parameters) {
596 addIssue(new Issue(errorKey, fatal, parameters));
603 public Iterator<Issue> iterator() {
604 return issues.iterator();
608 * Returns whether this check report does not contain any errors.
610 * @return {@code true} if this check report does not contain any
611 * errors, {@code false} if this check report does contain
614 public boolean isEmpty() {
615 return issues.isEmpty();
619 * Returns the number of issues in this check report.
621 * @return The number of issues
624 return issues.size();
630 * Container class for a single issue. An issue contains an error key
631 * that describes the error, and a fatality flag that determines whether
632 * the insert has to be aborted (if the flag is {@code true}) or if it
633 * can still be performed and only a warning should be generated (if the
634 * flag is {@code false}).
636 * @author <a href="mailto:bombe@pterodactylus.net">David āBombeā
639 public static class Issue {
641 /** The error key. */
642 private final String errorKey;
644 /** The fatality flag. */
645 private final boolean fatal;
647 /** Additional parameters. */
648 private String[] parameters;
651 * Creates a new issue.
658 * Any additional parameters
660 protected Issue(String errorKey, boolean fatal, String... parameters) {
661 this.errorKey = errorKey;
663 this.parameters = parameters;
667 * Returns the key of the encountered error.
669 * @return The error key
671 public String getErrorKey() {
676 * Returns whether the issue is fatal and the insert has to be
677 * aborted. Otherwise only a warning should be shown.
679 * @return {@code true} if the insert needs to be aborted, {@code
682 public boolean isFatal() {
687 * Returns any additional parameters.
689 * @return The additional parameters
691 public String[] getParameters() {