2 * jSite - ProjectInserter.java - Copyright © 2006–2011 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;
32 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.RedirectFileEntry;
47 import de.todesbaum.util.freenet.fcp2.Verbosity;
48 import de.todesbaum.util.io.StreamCopier.ProgressListener;
51 * Manages project inserts.
53 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
55 public class ProjectInserter implements FileScannerListener, Runnable {
58 private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
60 /** Random number for FCP instances. */
61 private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
63 /** Counter for FCP connection identifier. */
64 private static int counter = 0;
66 /** The list of insert listeners. */
67 private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
69 /** The freenet interface. */
70 protected Freenet7Interface freenetInterface;
72 /** The project to insert. */
73 protected Project project;
75 /** The file scanner. */
76 private FileScanner fileScanner;
78 /** Object used for synchronization. */
79 protected final Object lockObject = new Object();
81 /** The temp directory. */
82 private String tempDirectory;
84 /** The current connection. */
85 private Connection connection;
87 /** Whether the insert is cancelled. */
88 private volatile boolean cancelled = false;
90 /** Progress listener for payload transfers. */
91 private ProgressListener progressListener;
94 * Adds a listener to the list of registered listeners.
96 * @param insertListener
99 public void addInsertListener(InsertListener insertListener) {
100 insertListeners.add(insertListener);
104 * Removes a listener from the list of registered listeners.
106 * @param insertListener
107 * The listener to remove
109 public void removeInsertListener(InsertListener insertListener) {
110 insertListeners.remove(insertListener);
114 * Notifies all listeners that the project insert has started.
116 * @see InsertListener#projectInsertStarted(Project)
118 protected void fireProjectInsertStarted() {
119 for (InsertListener insertListener : insertListeners) {
120 insertListener.projectInsertStarted(project);
125 * Notifies all listeners that the insert has generated a URI.
127 * @see InsertListener#projectURIGenerated(Project, String)
131 protected void fireProjectURIGenerated(String uri) {
132 for (InsertListener insertListener : insertListeners) {
133 insertListener.projectURIGenerated(project, uri);
138 * Notifies all listeners that the insert has made some progress.
140 * @see InsertListener#projectUploadFinished(Project)
142 protected void fireProjectUploadFinished() {
143 for (InsertListener insertListener : insertListeners) {
144 insertListener.projectUploadFinished(project);
149 * Notifies all listeners that the insert has made some progress.
151 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
154 * The number of succeeded blocks
156 * The number of failed blocks
158 * The number of fatally failed blocks
160 * The total number of blocks
162 * <code>true</code> if the total number of blocks has already
163 * been finalized, <code>false</code> otherwise
165 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
166 for (InsertListener insertListener : insertListeners) {
167 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
172 * Notifies all listeners the project insert has finished.
174 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
176 * <code>true</code> if the project was inserted successfully,
177 * <code>false</code> if it failed
179 * The cause of the failure, if any
181 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
182 for (InsertListener insertListener : insertListeners) {
183 insertListener.projectInsertFinished(project, success, cause);
188 * Sets the project to insert.
191 * The project to insert
193 public void setProject(Project project) {
194 this.project = project;
198 * Sets the freenet interface to use.
200 * @param freenetInterface
201 * The freenet interface to use
203 public void setFreenetInterface(Freenet7Interface freenetInterface) {
204 this.freenetInterface = freenetInterface;
208 * Sets the temp directory to use.
210 * @param tempDirectory
211 * The temp directory to use, or {@code null} to use the system
214 public void setTempDirectory(String tempDirectory) {
215 this.tempDirectory = tempDirectory;
221 * @param progressListener
222 * Listener to notify on progress events
224 public void start(ProgressListener progressListener) {
226 this.progressListener = progressListener;
227 fileScanner = new FileScanner(project);
228 fileScanner.addFileScannerListener(this);
229 new Thread(fileScanner).start();
233 * Stops the current insert.
237 synchronized (lockObject) {
238 if (connection != null) {
239 connection.disconnect();
245 * Creates an input stream that delivers the given file, replacing edition
246 * tokens in the file’s content, if necessary.
249 * The name of the file
253 * The current edition
255 * An array containing a single long which is used to
256 * <em>return</em> the final length of the file, after all
258 * @return The input stream for the file
259 * @throws IOException
260 * if an I/O error occurs
262 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
263 File file = new File(project.getLocalPath(), filename);
264 length[0] = file.length();
265 return new FileInputStream(file);
269 * Creates a file entry suitable for handing in to
270 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
273 * The name and hash of the file to insert
275 * The current edition
276 * @return A file entry for the given file
278 private FileEntry createFileEntry(ScannedFile file, int edition) {
279 FileEntry fileEntry = null;
280 String filename = file.getFilename();
281 FileOption fileOption = project.getFileOption(filename);
282 if (fileOption.isInsert()) {
283 /* check if file was modified. */
284 if (file.getHash().equals(fileOption.getLastInsertHash())) {
285 /* only insert a redirect. */
286 return new RedirectFileEntry(filename, fileOption.getMimeType(), "SSK@" + project.getRequestURI() + "/" + project.getPath() + "-" + project.getEdition() + "/" + filename);
288 fileOption.setCurrentHash(file.getHash());
290 long[] fileLength = new long[1];
291 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
292 fileEntry = new DirectFileEntry(filename, fileOption.getMimeType(), fileEntryInputStream, fileLength[0]);
293 } catch (IOException ioe1) {
294 /* ignore, null is returned. */
297 if (fileOption.isInsertRedirect()) {
298 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
300 fileOption.setLastInsertHash("");
307 * Validates the given project. The project will be checked for any invalid
308 * conditions, such as invalid insert or request keys, missing path names,
309 * missing default file, and so on.
312 * The project to check
313 * @return The encountered warnings and errors
315 public static CheckReport validateProject(Project project) {
316 CheckReport checkReport = new CheckReport();
317 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
318 checkReport.addIssue("error.no-local-path", true);
320 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
321 checkReport.addIssue("error.no-path", true);
323 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
324 checkReport.addIssue("warning.empty-index", false);
326 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
327 if (!indexFile.exists()) {
328 checkReport.addIssue("error.index-missing", true);
331 String indexFile = project.getIndexFile();
332 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
333 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
334 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
335 checkReport.addIssue("warning.index-not-html", false);
337 Map<String, FileOption> fileOptions = project.getFileOptions();
338 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
339 boolean insert = fileOptionEntries.isEmpty();
340 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
341 String fileName = fileOptionEntry.getKey();
342 FileOption fileOption = fileOptionEntry.getValue();
343 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
344 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
345 checkReport.addIssue("error.index-not-inserted", true);
347 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
348 checkReport.addIssue("error.no-custom-key", true, fileName);
352 checkReport.addIssue("error.no-files-to-insert", true);
354 Set<String> fileNames = new HashSet<String>();
355 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
356 FileOption fileOption = fileOptionEntry.getValue();
357 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
358 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
361 String fileName = fileOptionEntry.getKey();
362 if (fileOption.hasChangedName()) {
363 fileName = fileOption.getChangedName();
365 logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
366 if (!fileNames.add(fileName)) {
367 checkReport.addIssue("error.duplicate-file", true, fileName);
377 fireProjectInsertStarted();
378 List<ScannedFile> files = fileScanner.getFiles();
380 /* create connection to node */
381 synchronized (lockObject) {
382 connection = freenetInterface.getConnection("project-insert-" + random + counter++);
384 connection.setTempDirectory(tempDirectory);
385 boolean connected = false;
386 Throwable cause = null;
388 connected = connection.connect();
389 } catch (IOException e1) {
393 if (!connected || cancelled) {
394 fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
398 Client client = new Client(connection);
401 int edition = project.getEdition();
402 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
403 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
404 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
405 putDir.setDefaultName(project.getIndexFile());
407 putDir.setVerbosity(Verbosity.ALL);
408 putDir.setMaxRetries(-1);
409 putDir.setEarlyEncode(false);
410 putDir.setManifestPutter(ManifestPutter.DEFAULT);
411 for (ScannedFile file : files) {
412 FileEntry fileEntry = createFileEntry(file, edition);
413 if (fileEntry != null) {
415 putDir.addFileEntry(fileEntry);
416 } catch (IOException ioe1) {
417 fireProjectInsertFinished(false, ioe1);
425 client.execute(putDir, progressListener);
426 fireProjectUploadFinished();
427 } catch (IOException ioe1) {
428 fireProjectInsertFinished(false, ioe1);
432 /* parse progress and success messages */
433 String finalURI = null;
434 boolean success = false;
435 boolean finished = false;
436 boolean disconnected = false;
437 while (!finished && !cancelled) {
438 Message message = client.readMessage();
439 finished = (message == null) || (disconnected = client.isDisconnected());
440 logger.log(Level.FINE, "Received message: " + message);
442 @SuppressWarnings("null")
443 String messageName = message.getName();
444 if ("URIGenerated".equals(messageName)) {
445 finalURI = message.get("URI");
446 fireProjectURIGenerated(finalURI);
448 if ("SimpleProgress".equals(messageName)) {
449 int total = Integer.parseInt(message.get("Total"));
450 int succeeded = Integer.parseInt(message.get("Succeeded"));
451 int fatal = Integer.parseInt(message.get("FatallyFailed"));
452 int failed = Integer.parseInt(message.get("Failed"));
453 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
454 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
456 success |= "PutSuccessful".equals(messageName);
457 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
461 /* post-insert work */
463 @SuppressWarnings("null")
464 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
465 int newEdition = Integer.parseInt(editionPart);
466 project.setEdition(newEdition);
467 project.setLastInsertionTime(System.currentTimeMillis());
468 project.copyHashes();
470 fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
474 // INTERFACE FileScannerListener
480 public void fileScannerFinished(FileScanner fileScanner) {
481 if (!fileScanner.isError()) {
482 new Thread(this).start();
484 fireProjectInsertFinished(false, null);
486 fileScanner.removeFileScannerListener(this);
490 * Container class that collects all warnings and errors that occured during
491 * {@link ProjectInserter#validateProject(Project) project validation}.
493 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
495 public static class CheckReport implements Iterable<Issue> {
497 /** The issures that occured. */
498 private final List<Issue> issues = new ArrayList<Issue>();
506 public void addIssue(Issue issue) {
511 * Creates an {@link Issue} from the given error key and fatality flag
512 * and {@link #addIssue(Issue) adds} it.
517 * {@code true} if the error is fatal, {@code false} if only
518 * a warning should be generated
520 * Any additional parameters
522 public void addIssue(String errorKey, boolean fatal, String... parameters) {
523 addIssue(new Issue(errorKey, fatal, parameters));
529 public Iterator<Issue> iterator() {
530 return issues.iterator();
534 * Returns whether this check report does not contain any errors.
536 * @return {@code true} if this check report does not contain any
537 * errors, {@code false} if this check report does contain
540 public boolean isEmpty() {
541 return issues.isEmpty();
545 * Returns the number of issues in this check report.
547 * @return The number of issues
550 return issues.size();
556 * Container class for a single issue. An issue contains an error key
557 * that describes the error, and a fatality flag that determines whether
558 * the insert has to be aborted (if the flag is {@code true}) or if it
559 * can still be performed and only a warning should be generated (if the
560 * flag is {@code false}).
562 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
565 public static class Issue {
567 /** The error key. */
568 private final String errorKey;
570 /** The fatality flag. */
571 private final boolean fatal;
573 /** Additional parameters. */
574 private String[] parameters;
577 * Creates a new issue.
584 * Any additional parameters
586 protected Issue(String errorKey, boolean fatal, String... parameters) {
587 this.errorKey = errorKey;
589 this.parameters = parameters;
593 * Returns the key of the encountered error.
595 * @return The error key
597 public String getErrorKey() {
602 * Returns whether the issue is fatal and the insert has to be
603 * aborted. Otherwise only a warning should be shown.
605 * @return {@code true} if the insert needs to be aborted, {@code
608 public boolean isFatal() {
613 * Returns any additional parameters.
615 * @return The additional parameters
617 public String[] getParameters() {