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;
101 * Adds a listener to the list of registered listeners.
103 * @param insertListener
104 * The listener to add
106 public void addInsertListener(InsertListener insertListener) {
107 insertListeners.add(insertListener);
111 * Removes a listener from the list of registered listeners.
113 * @param insertListener
114 * The listener to remove
116 public void removeInsertListener(InsertListener insertListener) {
117 insertListeners.remove(insertListener);
121 * Notifies all listeners that the project insert has started.
123 * @see InsertListener#projectInsertStarted(Project)
125 protected void fireProjectInsertStarted() {
126 for (InsertListener insertListener : insertListeners) {
127 insertListener.projectInsertStarted(project);
132 * Notifies all listeners that the insert has generated a URI.
134 * @see InsertListener#projectURIGenerated(Project, String)
138 protected void fireProjectURIGenerated(String uri) {
139 for (InsertListener insertListener : insertListeners) {
140 insertListener.projectURIGenerated(project, uri);
145 * Notifies all listeners that the insert has made some progress.
147 * @see InsertListener#projectUploadFinished(Project)
149 protected void fireProjectUploadFinished() {
150 for (InsertListener insertListener : insertListeners) {
151 insertListener.projectUploadFinished(project);
156 * Notifies all listeners that the insert has made some progress.
158 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
161 * The number of succeeded blocks
163 * The number of failed blocks
165 * The number of fatally failed blocks
167 * The total number of blocks
169 * <code>true</code> if the total number of blocks has already
170 * been finalized, <code>false</code> otherwise
172 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
173 for (InsertListener insertListener : insertListeners) {
174 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
179 * Notifies all listeners the project insert has finished.
181 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
183 * <code>true</code> if the project was inserted successfully,
184 * <code>false</code> if it failed
186 * The cause of the failure, if any
188 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
189 for (InsertListener insertListener : insertListeners) {
190 insertListener.projectInsertFinished(project, success, cause);
195 * Sets the project to insert.
198 * The project to insert
200 public void setProject(Project project) {
201 this.project = project;
205 * Sets the freenet interface to use.
207 * @param freenetInterface
208 * The freenet interface to use
210 public void setFreenetInterface(Freenet7Interface freenetInterface) {
211 this.freenetInterface = freenetInterface;
215 * Sets the temp directory to use.
217 * @param tempDirectory
218 * The temp directory to use, or {@code null} to use the system
221 public void setTempDirectory(String tempDirectory) {
222 this.tempDirectory = tempDirectory;
226 * Sets whether to use the “early encode“ flag for the insert.
228 * @param useEarlyEncode
229 * {@code true} to set the “early encode” flag for the insert,
230 * {@code false} otherwise
232 public void setUseEarlyEncode(boolean useEarlyEncode) {
233 this.useEarlyEncode = useEarlyEncode;
237 * Sets the insert priority.
240 * The insert priority
242 public void setPriority(PriorityClass priority) {
243 this.priority = priority;
249 * @param progressListener
250 * Listener to notify on progress events
252 public void start(ProgressListener progressListener) {
254 this.progressListener = progressListener;
255 fileScanner = new FileScanner(project);
256 fileScanner.addFileScannerListener(this);
257 new Thread(fileScanner).start();
261 * Stops the current insert.
265 synchronized (lockObject) {
266 if (connection != null) {
267 connection.disconnect();
273 * Creates an input stream that delivers the given file, replacing edition
274 * tokens in the file’s content, if necessary.
277 * The name of the file
281 * The current edition
283 * An array containing a single long which is used to
284 * <em>return</em> the final length of the file, after all
286 * @return The input stream for the file
287 * @throws IOException
288 * if an I/O error occurs
290 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
291 File file = new File(project.getLocalPath(), filename);
292 length[0] = file.length();
293 return new FileInputStream(file);
297 * Creates a file entry suitable for handing in to
298 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
301 * The name and hash of the file to insert
303 * The current edition
304 * @return A file entry for the given file
306 private FileEntry createFileEntry(ScannedFile file, int edition) {
307 FileEntry fileEntry = null;
308 String filename = file.getFilename();
309 FileOption fileOption = project.getFileOption(filename);
310 if (fileOption.isInsert()) {
311 fileOption.setCurrentHash(file.getHash());
312 /* check if file was modified. */
313 if (!fileOption.isForceInsert() && file.getHash().equals(fileOption.getLastInsertHash())) {
314 /* only insert a redirect. */
315 logger.log(Level.FINE, String.format("Inserting redirect to edition %d for %s.", fileOption.getLastInsertEdition(), filename));
316 return new RedirectFileEntry(filename, fileOption.getMimeType(), "SSK@" + project.getRequestURI() + "/" + project.getPath() + "-" + fileOption.getLastInsertEdition() + "/" + filename);
319 long[] fileLength = new long[1];
320 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
321 fileEntry = new DirectFileEntry(filename, fileOption.getMimeType(), fileEntryInputStream, fileLength[0]);
322 } catch (IOException ioe1) {
323 /* ignore, null is returned. */
326 if (fileOption.isInsertRedirect()) {
327 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
334 * Validates the given project. The project will be checked for any invalid
335 * conditions, such as invalid insert or request keys, missing path names,
336 * missing default file, and so on.
339 * The project to check
340 * @return The encountered warnings and errors
342 public static CheckReport validateProject(Project project) {
343 CheckReport checkReport = new CheckReport();
344 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
345 checkReport.addIssue("error.no-local-path", true);
347 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
348 checkReport.addIssue("error.no-path", true);
350 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
351 checkReport.addIssue("warning.empty-index", false);
353 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
354 if (!indexFile.exists()) {
355 checkReport.addIssue("error.index-missing", true);
358 String indexFile = project.getIndexFile();
359 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
360 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
361 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
362 checkReport.addIssue("warning.index-not-html", false);
364 Map<String, FileOption> fileOptions = project.getFileOptions();
365 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
366 boolean insert = fileOptionEntries.isEmpty();
367 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
368 String fileName = fileOptionEntry.getKey();
369 FileOption fileOption = fileOptionEntry.getValue();
370 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
371 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
372 checkReport.addIssue("error.index-not-inserted", true);
374 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
375 checkReport.addIssue("error.no-custom-key", true, fileName);
379 checkReport.addIssue("error.no-files-to-insert", true);
381 Set<String> fileNames = new HashSet<String>();
382 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
383 FileOption fileOption = fileOptionEntry.getValue();
384 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
385 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
388 String fileName = fileOptionEntry.getKey();
389 if (fileOption.hasChangedName()) {
390 fileName = fileOption.getChangedName();
392 logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
393 if (!fileNames.add(fileName)) {
394 checkReport.addIssue("error.duplicate-file", true, fileName);
404 fireProjectInsertStarted();
405 List<ScannedFile> files = fileScanner.getFiles();
407 /* create connection to node */
408 synchronized (lockObject) {
409 connection = freenetInterface.getConnection("project-insert-" + random + counter++);
411 connection.setTempDirectory(tempDirectory);
412 boolean connected = false;
413 Throwable cause = null;
415 connected = connection.connect();
416 } catch (IOException e1) {
420 if (!connected || cancelled) {
421 fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
425 Client client = new Client(connection);
428 int edition = project.getEdition();
429 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
430 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
431 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
432 putDir.setDefaultName(project.getIndexFile());
434 putDir.setVerbosity(Verbosity.ALL);
435 putDir.setMaxRetries(-1);
436 putDir.setEarlyEncode(useEarlyEncode);
437 putDir.setPriorityClass(priority);
438 putDir.setManifestPutter(ManifestPutter.DEFAULT);
439 for (ScannedFile file : files) {
440 FileEntry fileEntry = createFileEntry(file, edition);
441 if (fileEntry != null) {
443 putDir.addFileEntry(fileEntry);
444 } catch (IOException ioe1) {
445 fireProjectInsertFinished(false, ioe1);
453 client.execute(putDir, progressListener);
454 fireProjectUploadFinished();
455 } catch (IOException ioe1) {
456 fireProjectInsertFinished(false, ioe1);
460 /* parse progress and success messages */
461 String finalURI = null;
462 boolean success = false;
463 boolean finished = false;
464 boolean disconnected = false;
465 while (!finished && !cancelled) {
466 Message message = client.readMessage();
467 finished = (message == null) || (disconnected = client.isDisconnected());
468 logger.log(Level.FINE, "Received message: " + message);
470 @SuppressWarnings("null")
471 String messageName = message.getName();
472 if ("URIGenerated".equals(messageName)) {
473 finalURI = message.get("URI");
474 fireProjectURIGenerated(finalURI);
476 if ("SimpleProgress".equals(messageName)) {
477 int total = Integer.parseInt(message.get("Total"));
478 int succeeded = Integer.parseInt(message.get("Succeeded"));
479 int fatal = Integer.parseInt(message.get("FatallyFailed"));
480 int failed = Integer.parseInt(message.get("Failed"));
481 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
482 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
484 success |= "PutSuccessful".equals(messageName);
485 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
489 /* post-insert work */
491 @SuppressWarnings("null")
492 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
493 int newEdition = Integer.parseInt(editionPart);
494 project.setEdition(newEdition);
495 project.setLastInsertionTime(System.currentTimeMillis());
496 project.onSuccessfulInsert();
498 fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
502 // INTERFACE FileScannerListener
508 public void fileScannerFinished(FileScanner fileScanner) {
509 if (!fileScanner.isError()) {
510 new Thread(this).start();
512 fireProjectInsertFinished(false, null);
514 fileScanner.removeFileScannerListener(this);
518 * Container class that collects all warnings and errors that occured during
519 * {@link ProjectInserter#validateProject(Project) project validation}.
521 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
523 public static class CheckReport implements Iterable<Issue> {
525 /** The issures that occured. */
526 private final List<Issue> issues = new ArrayList<Issue>();
534 public void addIssue(Issue issue) {
539 * Creates an {@link Issue} from the given error key and fatality flag
540 * and {@link #addIssue(Issue) adds} it.
545 * {@code true} if the error is fatal, {@code false} if only
546 * a warning should be generated
548 * Any additional parameters
550 public void addIssue(String errorKey, boolean fatal, String... parameters) {
551 addIssue(new Issue(errorKey, fatal, parameters));
557 public Iterator<Issue> iterator() {
558 return issues.iterator();
562 * Returns whether this check report does not contain any errors.
564 * @return {@code true} if this check report does not contain any
565 * errors, {@code false} if this check report does contain
568 public boolean isEmpty() {
569 return issues.isEmpty();
573 * Returns the number of issues in this check report.
575 * @return The number of issues
578 return issues.size();
584 * Container class for a single issue. An issue contains an error key
585 * that describes the error, and a fatality flag that determines whether
586 * the insert has to be aborted (if the flag is {@code true}) or if it
587 * can still be performed and only a warning should be generated (if the
588 * flag is {@code false}).
590 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
593 public static class Issue {
595 /** The error key. */
596 private final String errorKey;
598 /** The fatality flag. */
599 private final boolean fatal;
601 /** Additional parameters. */
602 private String[] parameters;
605 * Creates a new issue.
612 * Any additional parameters
614 protected Issue(String errorKey, boolean fatal, String... parameters) {
615 this.errorKey = errorKey;
617 this.parameters = parameters;
621 * Returns the key of the encountered error.
623 * @return The error key
625 public String getErrorKey() {
630 * Returns whether the issue is fatal and the insert has to be
631 * aborted. Otherwise only a warning should be shown.
633 * @return {@code true} if the insert needs to be aborted, {@code
636 public boolean isFatal() {
641 * Returns any additional parameters.
643 * @return The additional parameters
645 public String[] getParameters() {