2 * jSite - a tool for uploading websites into Freenet
3 * Copyright (C) 2006 David Roden
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 package de.todesbaum.jsite.application;
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.List;
37 import java.util.Map.Entry;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
40 import java.util.zip.ZipEntry;
41 import java.util.zip.ZipOutputStream;
43 import de.todesbaum.jsite.gui.FileScanner;
44 import de.todesbaum.jsite.gui.FileScannerListener;
45 import de.todesbaum.util.freenet.fcp2.Client;
46 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
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 public void start(ProgressListener progressListener) {
231 this.progressListener = progressListener;
232 fileScanner = new FileScanner(project);
233 fileScanner.addFileScannerListener(this);
234 new Thread(fileScanner).start();
238 * Stops the current insert.
242 synchronized (lockObject) {
243 if (connection != null) {
244 connection.disconnect();
250 * Creates an input stream that delivers the given file, replacing edition
251 * tokens in the file’s content, if necessary.
254 * The name of the file
258 * The current edition
260 * An array containing a single long which is used to
261 * <em>return</em> the final length of the file, after all
263 * @return The input stream for the file
264 * @throws IOException
265 * if an I/O error occurs
267 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
268 File file = new File(project.getLocalPath(), filename);
269 length[0] = file.length();
270 if (!fileOption.getReplaceEdition()) {
271 return new FileInputStream(file);
273 ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
274 ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
275 FileInputStream fileInput = new FileInputStream(file);
277 outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
278 outputStream.addReplacement("$[URI]", project.getFinalRequestURI(0));
279 for (int index = 1; index <= fileOption.getEditionRange(); index++) {
280 outputStream.addReplacement("$[URI+" + index + "]", project.getFinalRequestURI(index));
281 outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
283 StreamCopier.copy(fileInput, outputStream, length[0]);
285 Closer.close(fileInput);
286 Closer.close(outputStream);
287 Closer.close(filteredByteOutputStream);
289 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
290 length[0] = filteredBytes.length;
291 return new ByteArrayInputStream(filteredBytes);
295 * Creates an input stream for a container.
297 * @param containerFiles
298 * All container definitions
299 * @param containerName
300 * The name of the container to create
302 * The current edition
303 * @param containerLength
304 * An array containing a single long which is used to
305 * <em>return</em> the final length of the container stream,
306 * after all replacements
307 * @return The input stream for the container
308 * @throws IOException
309 * if an I/O error occurs
311 private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
312 File tempFile = File.createTempFile("jsite", ".zip", (tempDirectory == null) ? null : new File(tempDirectory));
313 tempFile.deleteOnExit();
314 FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
315 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
317 for (String filename : containerFiles.get(containerName)) {
318 File dataFile = new File(project.getLocalPath(), filename);
319 if (dataFile.exists()) {
320 ZipEntry zipEntry = new ZipEntry(filename);
321 long[] fileLength = new long[1];
322 InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
324 zipOutputStream.putNextEntry(zipEntry);
325 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
327 zipOutputStream.closeEntry();
328 wrappedInputStream.close();
333 zipOutputStream.closeEntry();
334 Closer.close(zipOutputStream);
335 Closer.close(fileOutputStream);
338 containerLength[0] = tempFile.length();
339 return new FileInputStream(tempFile);
343 * Creates a file entry suitable for handing in to
344 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
347 * The name of the file to insert
349 * The current edition
350 * @param containerFiles
351 * The container definitions
352 * @return A file entry for the given file
354 private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
355 FileEntry fileEntry = null;
356 FileOption fileOption = project.getFileOption(filename);
357 if (filename.startsWith("/container/:")) {
358 String containerName = filename.substring("/container/:".length());
360 long[] containerLength = new long[1];
361 InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
362 fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
363 } catch (IOException ioe1) {
364 /* ignore, null is returned. */
367 if (fileOption.isInsert()) {
369 long[] fileLength = new long[1];
370 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
371 fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
372 } catch (IOException ioe1) {
373 /* ignore, null is returned. */
376 if (fileOption.isInsertRedirect()) {
377 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
385 * Creates container definitions.
388 * The list of all files
390 * The list of all containers
391 * @param containerFiles
392 * Empty map that will be filled with container definitions
394 private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
395 for (String filename : new ArrayList<String>(files)) {
396 FileOption fileOption = project.getFileOption(filename);
397 String containerName = fileOption.getContainer();
398 if (!containerName.equals("")) {
399 if (!containers.contains(containerName)) {
400 containers.add(containerName);
401 containerFiles.put(containerName, new ArrayList<String>());
402 /* hmm. looks like a hack to me. */
403 files.add("/container/:" + containerName);
405 containerFiles.get(containerName).add(filename);
406 files.remove(filename);
412 * Validates the given project. The project will be checked for any invalid
413 * conditions, such as invalid insert or request keys, missing path names,
414 * missing default file, and so on.
417 * The project to check
418 * @return The encountered warnings and errors
420 public static CheckReport validateProject(Project project) {
421 CheckReport checkReport = new CheckReport();
422 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
423 checkReport.addIssue("error.no-local-path", true);
425 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
426 checkReport.addIssue("error.no-path", true);
428 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
429 checkReport.addIssue("warning.empty-index", false);
431 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
432 if (!indexFile.exists()) {
433 checkReport.addIssue("error.index-missing", true);
436 String indexFile = project.getIndexFile();
437 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
438 if (hasIndexFile && !project.getFileOption(indexFile).getContainer().equals("")) {
439 checkReport.addIssue("warning.container-index", false);
441 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
442 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
443 checkReport.addIssue("warning.index-not-html", false);
445 Map<String, FileOption> fileOptions = project.getFileOptions();
446 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
447 boolean insert = fileOptionEntries.isEmpty();
448 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
449 String fileName = fileOptionEntry.getKey();
450 FileOption fileOption = fileOptionEntry.getValue();
451 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
452 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
453 checkReport.addIssue("error.index-not-inserted", true);
455 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
456 checkReport.addIssue("error.no-custom-key", true, fileName);
460 checkReport.addIssue("error.no-files-to-insert", true);
462 Set<String> fileNames = new HashSet<String>();
463 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
464 FileOption fileOption = fileOptionEntry.getValue();
465 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
466 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
469 String fileName = fileOptionEntry.getKey();
470 if (fileOption.hasChangedName()) {
471 fileName = fileOption.getChangedName();
473 logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
474 if (!fileNames.add(fileName)) {
475 checkReport.addIssue("error.duplicate-file", true, fileName);
485 fireProjectInsertStarted();
486 List<String> files = fileScanner.getFiles();
488 /* create connection to node */
489 synchronized (lockObject) {
490 connection = freenetInterface.getConnection("project-insert-" + random + counter++);
492 connection.setTempDirectory(tempDirectory);
493 boolean connected = false;
494 Throwable cause = null;
496 connected = connection.connect();
497 } catch (IOException e1) {
501 if (!connected || cancelled) {
502 fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
506 Client client = new Client(connection);
508 /* create containers */
509 final List<String> containers = new ArrayList<String>();
510 final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
511 createContainers(files, containers, containerFiles);
514 int edition = project.getEdition();
515 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
516 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
517 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
518 putDir.setDefaultName(project.getIndexFile());
520 putDir.setVerbosity(Verbosity.ALL);
521 putDir.setMaxRetries(-1);
522 putDir.setEarlyEncode(false);
523 for (String filename : files) {
524 FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
525 if (fileEntry != null) {
527 putDir.addFileEntry(fileEntry);
528 } catch (IOException ioe1) {
529 fireProjectInsertFinished(false, ioe1);
537 client.execute(putDir, progressListener);
538 fireProjectUploadFinished();
539 } catch (IOException ioe1) {
540 fireProjectInsertFinished(false, ioe1);
544 /* parse progress and success messages */
545 String finalURI = null;
546 boolean success = false;
547 boolean finished = false;
548 boolean disconnected = false;
549 while (!finished && !cancelled) {
550 Message message = client.readMessage();
551 finished = (message == null) || (disconnected = client.isDisconnected());
552 logger.log(Level.FINE, "Received message: " + message);
554 @SuppressWarnings("null")
555 String messageName = message.getName();
556 if ("URIGenerated".equals(messageName)) {
557 finalURI = message.get("URI");
558 fireProjectURIGenerated(finalURI);
560 if ("SimpleProgress".equals(messageName)) {
561 int total = Integer.parseInt(message.get("Total"));
562 int succeeded = Integer.parseInt(message.get("Succeeded"));
563 int fatal = Integer.parseInt(message.get("FatallyFailed"));
564 int failed = Integer.parseInt(message.get("Failed"));
565 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
566 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
568 success = "PutSuccessful".equals(messageName);
569 finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
573 /* post-insert work */
575 @SuppressWarnings("null")
576 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
577 int newEdition = Integer.parseInt(editionPart);
578 project.setEdition(newEdition);
579 project.setLastInsertionTime(System.currentTimeMillis());
581 fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
585 // INTERFACE FileScannerListener
591 public void fileScannerFinished(FileScanner fileScanner) {
592 if (!fileScanner.isError()) {
593 new Thread(this).start();
595 fireProjectInsertFinished(false, null);
597 fileScanner.removeFileScannerListener(this);
601 * Container class that collects all warnings and errors that occured during
602 * {@link ProjectInserter#validateProject(Project) project validation}.
604 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
606 public static class CheckReport implements Iterable<Issue> {
608 /** The issures that occured. */
609 private final List<Issue> issues = new ArrayList<Issue>();
617 public void addIssue(Issue issue) {
622 * Creates an {@link Issue} from the given error key and fatality flag
623 * and {@link #addIssue(Issue) adds} it.
628 * {@code true} if the error is fatal, {@code false} if only
629 * a warning should be generated
631 * Any additional parameters
633 public void addIssue(String errorKey, boolean fatal, String... parameters) {
634 addIssue(new Issue(errorKey, fatal, parameters));
640 public Iterator<Issue> iterator() {
641 return issues.iterator();
645 * Returns whether this check report does not contain any errors.
647 * @return {@code true} if this check report does not contain any
648 * errors, {@code false} if this check report does contain
651 public boolean isEmpty() {
652 return issues.isEmpty();
656 * Returns the number of issues in this check report.
658 * @return The number of issues
661 return issues.size();
667 * Container class for a single issue. An issue contains an error key
668 * that describes the error, and a fatality flag that determines whether
669 * the insert has to be aborted (if the flag is {@code true}) or if it
670 * can still be performed and only a warning should be generated (if the
671 * flag is {@code false}).
673 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
676 public static class Issue {
678 /** The error key. */
679 private final String errorKey;
681 /** The fatality flag. */
682 private final boolean fatal;
684 /** Additional parameters. */
685 private String[] parameters;
688 * Creates a new issue.
695 * Any additional parameters
697 protected Issue(String errorKey, boolean fatal, String... parameters) {
698 this.errorKey = errorKey;
700 this.parameters = parameters;
704 * Returns the key of the encountered error.
706 * @return The error key
708 public String getErrorKey() {
713 * Returns whether the issue is fatal and the insert has to be
714 * aborted. Otherwise only a warning should be shown.
716 * @return {@code true} if the insert needs to be aborted, {@code
719 public boolean isFatal() {
724 * Returns any additional parameters.
726 * @return The additional parameters
728 public String[] getParameters() {