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.logging.Level;
34 import java.util.logging.Logger;
36 import de.todesbaum.jsite.gui.FileScanner;
37 import de.todesbaum.jsite.gui.FileScanner.ScannedFile;
38 import de.todesbaum.jsite.gui.FileScannerListener;
39 import de.todesbaum.util.freenet.fcp2.Client;
40 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
41 import de.todesbaum.util.freenet.fcp2.ClientPutDir.ManifestPutter;
42 import de.todesbaum.util.freenet.fcp2.Connection;
43 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
44 import de.todesbaum.util.freenet.fcp2.FileEntry;
45 import de.todesbaum.util.freenet.fcp2.Message;
46 import de.todesbaum.util.freenet.fcp2.PriorityClass;
47 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
48 import de.todesbaum.util.freenet.fcp2.Verbosity;
49 import de.todesbaum.util.io.StreamCopier.ProgressListener;
52 * Manages project inserts.
54 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
56 public class ProjectInserter implements FileScannerListener, Runnable {
59 private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
61 /** Random number for FCP instances. */
62 private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
64 /** Counter for FCP connection identifier. */
65 private static int counter = 0;
67 /** The list of insert listeners. */
68 private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
70 /** The freenet interface. */
71 protected Freenet7Interface freenetInterface;
73 /** The project to insert. */
74 protected Project project;
76 /** The file scanner. */
77 private FileScanner fileScanner;
79 /** Object used for synchronization. */
80 protected final Object lockObject = new Object();
82 /** The temp directory. */
83 private String tempDirectory;
85 /** The current connection. */
86 private Connection connection;
88 /** Whether the insert is cancelled. */
89 private volatile boolean cancelled = false;
91 /** Progress listener for payload transfers. */
92 private ProgressListener progressListener;
94 /** Whether to use “early encode.” */
95 private boolean useEarlyEncode;
97 /** The insert priority. */
98 private PriorityClass priority;
100 /** The manifest putter. */
101 private ManifestPutter manifestPutter;
104 * Adds a listener to the list of registered listeners.
106 * @param insertListener
107 * The listener to add
109 public void addInsertListener(InsertListener insertListener) {
110 insertListeners.add(insertListener);
114 * Removes a listener from the list of registered listeners.
116 * @param insertListener
117 * The listener to remove
119 public void removeInsertListener(InsertListener insertListener) {
120 insertListeners.remove(insertListener);
124 * Notifies all listeners that the project insert has started.
126 * @see InsertListener#projectInsertStarted(Project)
128 protected void fireProjectInsertStarted() {
129 for (InsertListener insertListener : insertListeners) {
130 insertListener.projectInsertStarted(project);
135 * Notifies all listeners that the insert has generated a URI.
137 * @see InsertListener#projectURIGenerated(Project, String)
141 protected void fireProjectURIGenerated(String uri) {
142 for (InsertListener insertListener : insertListeners) {
143 insertListener.projectURIGenerated(project, uri);
148 * Notifies all listeners that the insert has made some progress.
150 * @see InsertListener#projectUploadFinished(Project)
152 protected void fireProjectUploadFinished() {
153 for (InsertListener insertListener : insertListeners) {
154 insertListener.projectUploadFinished(project);
159 * Notifies all listeners that the insert has made some progress.
161 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
164 * The number of succeeded blocks
166 * The number of failed blocks
168 * The number of fatally failed blocks
170 * The total number of blocks
172 * <code>true</code> if the total number of blocks has already
173 * been finalized, <code>false</code> otherwise
175 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
176 for (InsertListener insertListener : insertListeners) {
177 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
182 * Notifies all listeners the project insert has finished.
184 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
186 * <code>true</code> if the project was inserted successfully,
187 * <code>false</code> if it failed
189 * The cause of the failure, if any
191 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
192 for (InsertListener insertListener : insertListeners) {
193 insertListener.projectInsertFinished(project, success, cause);
198 * Sets the project to insert.
201 * The project to insert
203 public void setProject(Project project) {
204 this.project = project;
208 * Sets the freenet interface to use.
210 * @param freenetInterface
211 * The freenet interface to use
213 public void setFreenetInterface(Freenet7Interface freenetInterface) {
214 this.freenetInterface = freenetInterface;
218 * Sets the temp directory to use.
220 * @param tempDirectory
221 * The temp directory to use, or {@code null} to use the system
224 public void setTempDirectory(String tempDirectory) {
225 this.tempDirectory = tempDirectory;
229 * Sets whether to use the “early encode“ flag for the insert.
231 * @param useEarlyEncode
232 * {@code true} to set the “early encode” flag for the insert,
233 * {@code false} otherwise
235 public void setUseEarlyEncode(boolean useEarlyEncode) {
236 this.useEarlyEncode = useEarlyEncode;
240 * Sets the insert priority.
243 * The insert priority
245 public void setPriority(PriorityClass priority) {
246 this.priority = priority;
250 * Sets the manifest putter to use for inserts.
252 * @param manifestPutter
253 * The manifest putter to use
255 public void setManifestPutter(ManifestPutter manifestPutter) {
256 this.manifestPutter = manifestPutter;
262 * @param progressListener
263 * Listener to notify on progress events
265 public void start(ProgressListener progressListener) {
267 this.progressListener = progressListener;
268 fileScanner = new FileScanner(project);
269 fileScanner.addFileScannerListener(this);
270 new Thread(fileScanner).start();
274 * Stops the current insert.
278 synchronized (lockObject) {
279 if (connection != null) {
280 connection.disconnect();
286 * Creates an input stream that delivers the given file, replacing edition
287 * tokens in the file’s content, if necessary.
290 * The name of the file
294 * The current edition
296 * An array containing a single long which is used to
297 * <em>return</em> the final length of the file, after all
299 * @return The input stream for the file
300 * @throws IOException
301 * if an I/O error occurs
303 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
304 File file = new File(project.getLocalPath(), filename);
305 length[0] = file.length();
306 return new FileInputStream(file);
310 * Creates a file entry suitable for handing in to
311 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
314 * The name and hash of the file to insert
316 * The current edition
317 * @return A file entry for the given file
319 private FileEntry createFileEntry(ScannedFile file, int edition) {
320 FileEntry fileEntry = null;
321 String filename = file.getFilename();
322 FileOption fileOption = project.getFileOption(filename);
323 if (fileOption.isInsert()) {
324 fileOption.setCurrentHash(file.getHash());
325 /* check if file was modified. */
326 if (!fileOption.isForceInsert() && file.getHash().equals(fileOption.getLastInsertHash())) {
327 /* only insert a redirect. */
328 logger.log(Level.FINE, String.format("Inserting redirect to edition %d for %s.", fileOption.getLastInsertEdition(), filename));
329 return new RedirectFileEntry(fileOption.hasChangedName() ? fileOption.getChangedName() : filename, fileOption.getMimeType(), "SSK@" + project.getRequestURI() + "/" + project.getPath() + "-" + fileOption.getLastInsertEdition() + "/" + fileOption.getLastInsertFilename());
332 long[] fileLength = new long[1];
333 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
334 fileEntry = new DirectFileEntry(fileOption.hasChangedName() ? fileOption.getChangedName() : filename, fileOption.getMimeType(), fileEntryInputStream, fileLength[0]);
335 } catch (IOException ioe1) {
336 /* ignore, null is returned. */
339 if (fileOption.isInsertRedirect()) {
340 fileEntry = new RedirectFileEntry(fileOption.hasChangedName() ? fileOption.getChangedName() : filename, fileOption.getMimeType(), fileOption.getCustomKey());
347 * Validates the given project. The project will be checked for any invalid
348 * conditions, such as invalid insert or request keys, missing path names,
349 * missing default file, and so on.
352 * The project to check
353 * @return The encountered warnings and errors
355 public static CheckReport validateProject(Project project) {
356 CheckReport checkReport = new CheckReport();
357 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
358 checkReport.addIssue("error.no-local-path", true);
360 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
361 checkReport.addIssue("error.no-path", true);
363 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
364 checkReport.addIssue("warning.empty-index", false);
366 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
367 if (!indexFile.exists()) {
368 checkReport.addIssue("error.index-missing", true);
371 String indexFile = project.getIndexFile();
372 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
373 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
374 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
375 checkReport.addIssue("warning.index-not-html", false);
377 Map<String, FileOption> fileOptions = project.getFileOptions();
378 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
379 boolean insert = fileOptionEntries.isEmpty();
380 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
381 String fileName = fileOptionEntry.getKey();
382 FileOption fileOption = fileOptionEntry.getValue();
383 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
384 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
385 checkReport.addIssue("error.index-not-inserted", true);
387 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
388 checkReport.addIssue("error.no-custom-key", true, fileName);
392 checkReport.addIssue("error.no-files-to-insert", true);
394 Set<String> fileNames = new HashSet<String>();
395 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
396 FileOption fileOption = fileOptionEntry.getValue();
397 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
398 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
401 String fileName = fileOptionEntry.getKey();
402 if (fileOption.hasChangedName()) {
403 fileName = fileOption.getChangedName();
405 logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
406 if (!fileNames.add(fileName)) {
407 checkReport.addIssue("error.duplicate-file", true, fileName);
417 fireProjectInsertStarted();
418 List<ScannedFile> files = fileScanner.getFiles();
420 /* create connection to node */
421 synchronized (lockObject) {
422 connection = freenetInterface.getConnection("project-insert-" + random + counter++);
424 connection.setTempDirectory(tempDirectory);
425 boolean connected = false;
426 Throwable cause = null;
428 connected = connection.connect();
429 } catch (IOException e1) {
433 if (!connected || cancelled) {
434 fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
438 Client client = new Client(connection);
441 int edition = project.getEdition();
442 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
443 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
444 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
445 putDir.setDefaultName(project.getIndexFile());
447 putDir.setVerbosity(Verbosity.ALL);
448 putDir.setMaxRetries(-1);
449 putDir.setEarlyEncode(useEarlyEncode);
450 putDir.setPriorityClass(priority);
451 putDir.setManifestPutter(manifestPutter);
452 for (ScannedFile file : files) {
453 FileEntry fileEntry = createFileEntry(file, edition);
454 if (fileEntry != null) {
456 putDir.addFileEntry(fileEntry);
457 } catch (IOException ioe1) {
458 fireProjectInsertFinished(false, ioe1);
466 client.execute(putDir, progressListener);
467 fireProjectUploadFinished();
468 } catch (IOException ioe1) {
469 fireProjectInsertFinished(false, ioe1);
473 /* parse progress and success messages */
474 String finalURI = null;
475 boolean success = false;
476 boolean finished = false;
477 boolean disconnected = false;
478 while (!finished && !cancelled) {
479 Message message = client.readMessage();
480 finished = (message == null) || (disconnected = client.isDisconnected());
481 logger.log(Level.FINE, "Received message: " + message);
483 @SuppressWarnings("null")
484 String messageName = message.getName();
485 if ("URIGenerated".equals(messageName)) {
486 finalURI = message.get("URI");
487 fireProjectURIGenerated(finalURI);
489 if ("SimpleProgress".equals(messageName)) {
490 int total = Integer.parseInt(message.get("Total"));
491 int succeeded = Integer.parseInt(message.get("Succeeded"));
492 int fatal = Integer.parseInt(message.get("FatallyFailed"));
493 int failed = Integer.parseInt(message.get("Failed"));
494 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
495 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
497 success |= "PutSuccessful".equals(messageName);
498 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
502 /* post-insert work */
504 @SuppressWarnings("null")
505 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
506 int newEdition = Integer.parseInt(editionPart);
507 project.setEdition(newEdition);
508 project.setLastInsertionTime(System.currentTimeMillis());
509 project.onSuccessfulInsert();
511 fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
515 // INTERFACE FileScannerListener
521 public void fileScannerFinished(FileScanner fileScanner) {
522 if (!fileScanner.isError()) {
523 new Thread(this).start();
525 fireProjectInsertFinished(false, null);
527 fileScanner.removeFileScannerListener(this);
531 * Container class that collects all warnings and errors that occured during
532 * {@link ProjectInserter#validateProject(Project) project validation}.
534 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
536 public static class CheckReport implements Iterable<Issue> {
538 /** The issures that occured. */
539 private final List<Issue> issues = new ArrayList<Issue>();
547 public void addIssue(Issue issue) {
552 * Creates an {@link Issue} from the given error key and fatality flag
553 * and {@link #addIssue(Issue) adds} it.
558 * {@code true} if the error is fatal, {@code false} if only
559 * a warning should be generated
561 * Any additional parameters
563 public void addIssue(String errorKey, boolean fatal, String... parameters) {
564 addIssue(new Issue(errorKey, fatal, parameters));
570 public Iterator<Issue> iterator() {
571 return issues.iterator();
575 * Returns whether this check report does not contain any errors.
577 * @return {@code true} if this check report does not contain any
578 * errors, {@code false} if this check report does contain
581 public boolean isEmpty() {
582 return issues.isEmpty();
586 * Returns the number of issues in this check report.
588 * @return The number of issues
591 return issues.size();
597 * Container class for a single issue. An issue contains an error key
598 * that describes the error, and a fatality flag that determines whether
599 * the insert has to be aborted (if the flag is {@code true}) or if it
600 * can still be performed and only a warning should be generated (if the
601 * flag is {@code false}).
603 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
606 public static class Issue {
608 /** The error key. */
609 private final String errorKey;
611 /** The fatality flag. */
612 private final boolean fatal;
614 /** Additional parameters. */
615 private String[] parameters;
618 * Creates a new issue.
625 * Any additional parameters
627 protected Issue(String errorKey, boolean fatal, String... parameters) {
628 this.errorKey = errorKey;
630 this.parameters = parameters;
634 * Returns the key of the encountered error.
636 * @return The error key
638 public String getErrorKey() {
643 * Returns whether the issue is fatal and the insert has to be
644 * aborted. Otherwise only a warning should be shown.
646 * @return {@code true} if the insert needs to be aborted, {@code
649 public boolean isFatal() {
654 * Returns any additional parameters.
656 * @return The additional parameters
658 public String[] getParameters() {