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;
21 import java.io.ByteArrayInputStream;
22 import java.io.ByteArrayOutputStream;
24 import java.io.FileInputStream;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
39 import java.util.zip.ZipEntry;
40 import java.util.zip.ZipOutputStream;
42 import de.todesbaum.jsite.gui.FileScanner;
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.ClientPutDir.ManifestPutter;
47 import de.todesbaum.util.freenet.fcp2.Connection;
48 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
49 import de.todesbaum.util.freenet.fcp2.FileEntry;
50 import de.todesbaum.util.freenet.fcp2.Message;
51 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
52 import de.todesbaum.util.freenet.fcp2.Verbosity;
53 import de.todesbaum.util.io.Closer;
54 import de.todesbaum.util.io.ReplacingOutputStream;
55 import de.todesbaum.util.io.StreamCopier;
56 import de.todesbaum.util.io.StreamCopier.ProgressListener;
59 * Manages project inserts.
61 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
63 public class ProjectInserter implements FileScannerListener, Runnable {
66 private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
68 /** Random number for FCP instances. */
69 private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
71 /** Counter for FCP connection identifier. */
72 private static int counter = 0;
74 /** The list of insert listeners. */
75 private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
77 /** The freenet interface. */
78 protected Freenet7Interface freenetInterface;
80 /** The project to insert. */
81 protected Project project;
83 /** The file scanner. */
84 private FileScanner fileScanner;
86 /** Object used for synchronization. */
87 protected final Object lockObject = new Object();
89 /** The temp directory. */
90 private String tempDirectory;
92 /** The current connection. */
93 private Connection connection;
95 /** Whether the insert is cancelled. */
96 private volatile boolean cancelled = false;
98 /** Progress listener for payload transfers. */
99 private ProgressListener progressListener;
102 * Adds a listener to the list of registered listeners.
104 * @param insertListener
105 * The listener to add
107 public void addInsertListener(InsertListener insertListener) {
108 insertListeners.add(insertListener);
112 * Removes a listener from the list of registered listeners.
114 * @param insertListener
115 * The listener to remove
117 public void removeInsertListener(InsertListener insertListener) {
118 insertListeners.remove(insertListener);
122 * Notifies all listeners that the project insert has started.
124 * @see InsertListener#projectInsertStarted(Project)
126 protected void fireProjectInsertStarted() {
127 for (InsertListener insertListener : insertListeners) {
128 insertListener.projectInsertStarted(project);
133 * Notifies all listeners that the insert has generated a URI.
135 * @see InsertListener#projectURIGenerated(Project, String)
139 protected void fireProjectURIGenerated(String uri) {
140 for (InsertListener insertListener : insertListeners) {
141 insertListener.projectURIGenerated(project, uri);
146 * Notifies all listeners that the insert has made some progress.
148 * @see InsertListener#projectUploadFinished(Project)
150 protected void fireProjectUploadFinished() {
151 for (InsertListener insertListener : insertListeners) {
152 insertListener.projectUploadFinished(project);
157 * Notifies all listeners that the insert has made some progress.
159 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
162 * The number of succeeded blocks
164 * The number of failed blocks
166 * The number of fatally failed blocks
168 * The total number of blocks
170 * <code>true</code> if the total number of blocks has already
171 * been finalized, <code>false</code> otherwise
173 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
174 for (InsertListener insertListener : insertListeners) {
175 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
180 * Notifies all listeners the project insert has finished.
182 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
184 * <code>true</code> if the project was inserted successfully,
185 * <code>false</code> if it failed
187 * The cause of the failure, if any
189 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
190 for (InsertListener insertListener : insertListeners) {
191 insertListener.projectInsertFinished(project, success, cause);
196 * Sets the project to insert.
199 * The project to insert
201 public void setProject(Project project) {
202 this.project = project;
206 * Sets the freenet interface to use.
208 * @param freenetInterface
209 * The freenet interface to use
211 public void setFreenetInterface(Freenet7Interface freenetInterface) {
212 this.freenetInterface = freenetInterface;
216 * Sets the temp directory to use.
218 * @param tempDirectory
219 * The temp directory to use, or {@code null} to use the system
222 public void setTempDirectory(String tempDirectory) {
223 this.tempDirectory = tempDirectory;
229 * @param progressListener
230 * Listener to notify on progress events
232 public void start(ProgressListener progressListener) {
234 this.progressListener = progressListener;
235 fileScanner = new FileScanner(project);
236 fileScanner.addFileScannerListener(this);
237 new Thread(fileScanner).start();
241 * Stops the current insert.
245 synchronized (lockObject) {
246 if (connection != null) {
247 connection.disconnect();
253 * Creates an input stream that delivers the given file, replacing edition
254 * tokens in the file’s content, if necessary.
257 * The name of the file
261 * The current edition
263 * An array containing a single long which is used to
264 * <em>return</em> the final length of the file, after all
266 * @return The input stream for the file
267 * @throws IOException
268 * if an I/O error occurs
270 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
271 File file = new File(project.getLocalPath(), filename);
272 length[0] = file.length();
273 if (!fileOption.getReplaceEdition()) {
274 return new FileInputStream(file);
276 ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
277 ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
278 FileInputStream fileInput = new FileInputStream(file);
280 outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
281 outputStream.addReplacement("$[URI]", project.getFinalRequestURI(0));
282 for (int index = 1; index <= fileOption.getEditionRange(); index++) {
283 outputStream.addReplacement("$[URI+" + index + "]", project.getFinalRequestURI(index));
284 outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
286 StreamCopier.copy(fileInput, outputStream, length[0]);
288 Closer.close(fileInput);
289 Closer.close(outputStream);
290 Closer.close(filteredByteOutputStream);
292 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
293 length[0] = filteredBytes.length;
294 return new ByteArrayInputStream(filteredBytes);
298 * Creates an input stream for a container.
300 * @param containerFiles
301 * All container definitions
302 * @param containerName
303 * The name of the container to create
305 * The current edition
306 * @param containerLength
307 * An array containing a single long which is used to
308 * <em>return</em> the final length of the container stream,
309 * after all replacements
310 * @return The input stream for the container
311 * @throws IOException
312 * if an I/O error occurs
314 private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
315 File tempFile = File.createTempFile("jsite", ".zip", (tempDirectory == null) ? null : new File(tempDirectory));
316 tempFile.deleteOnExit();
317 FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
318 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
320 for (String filename : containerFiles.get(containerName)) {
321 File dataFile = new File(project.getLocalPath(), filename);
322 if (dataFile.exists()) {
323 ZipEntry zipEntry = new ZipEntry(filename);
324 long[] fileLength = new long[1];
325 InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
327 zipOutputStream.putNextEntry(zipEntry);
328 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
330 zipOutputStream.closeEntry();
331 wrappedInputStream.close();
336 zipOutputStream.closeEntry();
337 Closer.close(zipOutputStream);
338 Closer.close(fileOutputStream);
341 containerLength[0] = tempFile.length();
342 return new FileInputStream(tempFile);
346 * Creates a file entry suitable for handing in to
347 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
350 * The name of the file to insert
352 * The current edition
353 * @param containerFiles
354 * The container definitions
355 * @return A file entry for the given file
357 private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
358 FileEntry fileEntry = null;
359 FileOption fileOption = project.getFileOption(filename);
360 if (filename.startsWith("/container/:")) {
361 String containerName = filename.substring("/container/:".length());
363 long[] containerLength = new long[1];
364 InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
365 fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
366 } catch (IOException ioe1) {
367 /* ignore, null is returned. */
370 if (fileOption.isInsert()) {
372 long[] fileLength = new long[1];
373 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
374 fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
375 } catch (IOException ioe1) {
376 /* ignore, null is returned. */
379 if (fileOption.isInsertRedirect()) {
380 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
388 * Creates container definitions.
391 * The list of all files
393 * The list of all containers
394 * @param containerFiles
395 * Empty map that will be filled with container definitions
397 private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
398 for (String filename : new ArrayList<String>(files)) {
399 FileOption fileOption = project.getFileOption(filename);
400 String containerName = fileOption.getContainer();
401 if (!containerName.equals("")) {
402 if (!containers.contains(containerName)) {
403 containers.add(containerName);
404 containerFiles.put(containerName, new ArrayList<String>());
405 /* hmm. looks like a hack to me. */
406 files.add("/container/:" + containerName);
408 containerFiles.get(containerName).add(filename);
409 files.remove(filename);
415 * Validates the given project. The project will be checked for any invalid
416 * conditions, such as invalid insert or request keys, missing path names,
417 * missing default file, and so on.
420 * The project to check
421 * @return The encountered warnings and errors
423 public static CheckReport validateProject(Project project) {
424 CheckReport checkReport = new CheckReport();
425 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
426 checkReport.addIssue("error.no-local-path", true);
428 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
429 checkReport.addIssue("error.no-path", true);
431 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
432 checkReport.addIssue("warning.empty-index", false);
434 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
435 if (!indexFile.exists()) {
436 checkReport.addIssue("error.index-missing", true);
439 String indexFile = project.getIndexFile();
440 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
441 if (hasIndexFile && !project.getFileOption(indexFile).getContainer().equals("")) {
442 checkReport.addIssue("warning.container-index", false);
444 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
445 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
446 checkReport.addIssue("warning.index-not-html", false);
448 Map<String, FileOption> fileOptions = project.getFileOptions();
449 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
450 boolean insert = fileOptionEntries.isEmpty();
451 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
452 String fileName = fileOptionEntry.getKey();
453 FileOption fileOption = fileOptionEntry.getValue();
454 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
455 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
456 checkReport.addIssue("error.index-not-inserted", true);
458 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
459 checkReport.addIssue("error.no-custom-key", true, fileName);
463 checkReport.addIssue("error.no-files-to-insert", true);
465 Set<String> fileNames = new HashSet<String>();
466 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
467 FileOption fileOption = fileOptionEntry.getValue();
468 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
469 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
472 String fileName = fileOptionEntry.getKey();
473 if (fileOption.hasChangedName()) {
474 fileName = fileOption.getChangedName();
476 logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
477 if (!fileNames.add(fileName)) {
478 checkReport.addIssue("error.duplicate-file", true, fileName);
488 fireProjectInsertStarted();
489 List<String> files = fileScanner.getFiles();
491 /* create connection to node */
492 synchronized (lockObject) {
493 connection = freenetInterface.getConnection("project-insert-" + random + counter++);
495 connection.setTempDirectory(tempDirectory);
496 boolean connected = false;
497 Throwable cause = null;
499 connected = connection.connect();
500 } catch (IOException e1) {
504 if (!connected || cancelled) {
505 fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
509 Client client = new Client(connection);
511 /* create containers */
512 final List<String> containers = new ArrayList<String>();
513 final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
514 createContainers(files, containers, containerFiles);
517 int edition = project.getEdition();
518 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
519 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
520 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
521 putDir.setDefaultName(project.getIndexFile());
523 putDir.setVerbosity(Verbosity.ALL);
524 putDir.setMaxRetries(-1);
525 putDir.setEarlyEncode(false);
526 putDir.setManifestPutter(ManifestPutter.DEFAULT);
527 for (String filename : files) {
528 FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
529 if (fileEntry != null) {
531 putDir.addFileEntry(fileEntry);
532 } catch (IOException ioe1) {
533 fireProjectInsertFinished(false, ioe1);
541 client.execute(putDir, progressListener);
542 fireProjectUploadFinished();
543 } catch (IOException ioe1) {
544 fireProjectInsertFinished(false, ioe1);
548 /* parse progress and success messages */
549 String finalURI = null;
550 boolean success = false;
551 boolean finished = false;
552 boolean disconnected = false;
553 while (!finished && !cancelled) {
554 Message message = client.readMessage();
555 finished = (message == null) || (disconnected = client.isDisconnected());
556 logger.log(Level.FINE, "Received message: " + message);
558 @SuppressWarnings("null")
559 String messageName = message.getName();
560 if ("URIGenerated".equals(messageName)) {
561 finalURI = message.get("URI");
562 fireProjectURIGenerated(finalURI);
564 if ("SimpleProgress".equals(messageName)) {
565 int total = Integer.parseInt(message.get("Total"));
566 int succeeded = Integer.parseInt(message.get("Succeeded"));
567 int fatal = Integer.parseInt(message.get("FatallyFailed"));
568 int failed = Integer.parseInt(message.get("Failed"));
569 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
570 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
572 success |= "PutSuccessful".equals(messageName);
573 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
577 /* post-insert work */
579 @SuppressWarnings("null")
580 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
581 int newEdition = Integer.parseInt(editionPart);
582 project.setEdition(newEdition);
583 project.setLastInsertionTime(System.currentTimeMillis());
585 fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
589 // INTERFACE FileScannerListener
595 public void fileScannerFinished(FileScanner fileScanner) {
596 if (!fileScanner.isError()) {
597 new Thread(this).start();
599 fireProjectInsertFinished(false, null);
601 fileScanner.removeFileScannerListener(this);
605 * Container class that collects all warnings and errors that occured during
606 * {@link ProjectInserter#validateProject(Project) project validation}.
608 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
610 public static class CheckReport implements Iterable<Issue> {
612 /** The issures that occured. */
613 private final List<Issue> issues = new ArrayList<Issue>();
621 public void addIssue(Issue issue) {
626 * Creates an {@link Issue} from the given error key and fatality flag
627 * and {@link #addIssue(Issue) adds} it.
632 * {@code true} if the error is fatal, {@code false} if only
633 * a warning should be generated
635 * Any additional parameters
637 public void addIssue(String errorKey, boolean fatal, String... parameters) {
638 addIssue(new Issue(errorKey, fatal, parameters));
644 public Iterator<Issue> iterator() {
645 return issues.iterator();
649 * Returns whether this check report does not contain any errors.
651 * @return {@code true} if this check report does not contain any
652 * errors, {@code false} if this check report does contain
655 public boolean isEmpty() {
656 return issues.isEmpty();
660 * Returns the number of issues in this check report.
662 * @return The number of issues
665 return issues.size();
671 * Container class for a single issue. An issue contains an error key
672 * that describes the error, and a fatality flag that determines whether
673 * the insert has to be aborted (if the flag is {@code true}) or if it
674 * can still be performed and only a warning should be generated (if the
675 * flag is {@code false}).
677 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
680 public static class Issue {
682 /** The error key. */
683 private final String errorKey;
685 /** The fatality flag. */
686 private final boolean fatal;
688 /** Additional parameters. */
689 private String[] parameters;
692 * Creates a new issue.
699 * Any additional parameters
701 protected Issue(String errorKey, boolean fatal, String... parameters) {
702 this.errorKey = errorKey;
704 this.parameters = parameters;
708 * Returns the key of the encountered error.
710 * @return The error key
712 public String getErrorKey() {
717 * Returns whether the issue is fatal and the insert has to be
718 * aborted. Otherwise only a warning should be shown.
720 * @return {@code true} if the insert needs to be aborted, {@code
723 public boolean isFatal() {
728 * Returns any additional parameters.
730 * @return The additional parameters
732 public String[] getParameters() {