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;
58 * Manages project inserts.
60 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
62 public class ProjectInserter implements FileScannerListener, Runnable {
65 private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
67 /** Random number for FCP instances. */
68 private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
70 /** Counter for FCP connection identifier. */
71 private static int counter = 0;
73 /** The list of insert listeners. */
74 private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
76 /** The freenet interface. */
77 protected Freenet7Interface freenetInterface;
79 /** The project to insert. */
80 protected Project project;
82 /** The file scanner. */
83 private FileScanner fileScanner;
85 /** Object used for synchronization. */
86 protected final Object lockObject = new Object();
88 /** The temp directory. */
89 private String tempDirectory;
91 /** The current connection. */
92 private Connection connection;
94 /** Whether the insert is cancelled. */
95 private volatile boolean cancelled = false;
98 * Adds a listener to the list of registered listeners.
100 * @param insertListener
101 * The listener to add
103 public void addInsertListener(InsertListener insertListener) {
104 insertListeners.add(insertListener);
108 * Removes a listener from the list of registered listeners.
110 * @param insertListener
111 * The listener to remove
113 public void removeInsertListener(InsertListener insertListener) {
114 insertListeners.remove(insertListener);
118 * Notifies all listeners that the project insert has started.
120 * @see InsertListener#projectInsertStarted(Project)
122 protected void fireProjectInsertStarted() {
123 for (InsertListener insertListener : insertListeners) {
124 insertListener.projectInsertStarted(project);
129 * Notifies all listeners that the insert has generated a URI.
131 * @see InsertListener#projectURIGenerated(Project, String)
135 protected void fireProjectURIGenerated(String uri) {
136 for (InsertListener insertListener : insertListeners) {
137 insertListener.projectURIGenerated(project, uri);
142 * Notifies all listeners that the insert has made some progress.
144 * @see InsertListener#projectUploadFinished(Project)
146 protected void fireProjectUploadFinished() {
147 for (InsertListener insertListener : insertListeners) {
148 insertListener.projectUploadFinished(project);
153 * Notifies all listeners that the insert has made some progress.
155 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
158 * The number of succeeded blocks
160 * The number of failed blocks
162 * The number of fatally failed blocks
164 * The total number of blocks
166 * <code>true</code> if the total number of blocks has already
167 * been finalized, <code>false</code> otherwise
169 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
170 for (InsertListener insertListener : insertListeners) {
171 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
176 * Notifies all listeners the project insert has finished.
178 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
180 * <code>true</code> if the project was inserted successfully,
181 * <code>false</code> if it failed
183 * The cause of the failure, if any
185 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
186 for (InsertListener insertListener : insertListeners) {
187 insertListener.projectInsertFinished(project, success, cause);
192 * Sets the project to insert.
195 * The project to insert
197 public void setProject(Project project) {
198 this.project = project;
202 * Sets the freenet interface to use.
204 * @param freenetInterface
205 * The freenet interface to use
207 public void setFreenetInterface(Freenet7Interface freenetInterface) {
208 this.freenetInterface = freenetInterface;
212 * Sets the temp directory to use.
214 * @param tempDirectory
215 * The temp directory to use, or {@code null} to use the system
218 public void setTempDirectory(String tempDirectory) {
219 this.tempDirectory = tempDirectory;
225 public void start() {
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 if (!fileOption.getReplaceEdition()) {
266 return new FileInputStream(file);
268 ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
269 ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
270 FileInputStream fileInput = new FileInputStream(file);
272 outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
273 outputStream.addReplacement("$[URI]", project.getFinalRequestURI(0));
274 for (int index = 1; index <= fileOption.getEditionRange(); index++) {
275 outputStream.addReplacement("$[URI+" + index + "]", project.getFinalRequestURI(index));
276 outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
278 StreamCopier.copy(fileInput, outputStream, length[0]);
280 Closer.close(fileInput);
281 Closer.close(outputStream);
282 Closer.close(filteredByteOutputStream);
284 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
285 length[0] = filteredBytes.length;
286 return new ByteArrayInputStream(filteredBytes);
290 * Creates an input stream for a container.
292 * @param containerFiles
293 * All container definitions
294 * @param containerName
295 * The name of the container to create
297 * The current edition
298 * @param containerLength
299 * An array containing a single long which is used to
300 * <em>return</em> the final length of the container stream,
301 * after all replacements
302 * @return The input stream for the container
303 * @throws IOException
304 * if an I/O error occurs
306 private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
307 File tempFile = File.createTempFile("jsite", ".zip", (tempDirectory == null) ? null : new File(tempDirectory));
308 tempFile.deleteOnExit();
309 FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
310 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
312 for (String filename : containerFiles.get(containerName)) {
313 File dataFile = new File(project.getLocalPath(), filename);
314 if (dataFile.exists()) {
315 ZipEntry zipEntry = new ZipEntry(filename);
316 long[] fileLength = new long[1];
317 InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
319 zipOutputStream.putNextEntry(zipEntry);
320 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
322 zipOutputStream.closeEntry();
323 wrappedInputStream.close();
328 zipOutputStream.closeEntry();
329 Closer.close(zipOutputStream);
330 Closer.close(fileOutputStream);
333 containerLength[0] = tempFile.length();
334 return new FileInputStream(tempFile);
338 * Creates a file entry suitable for handing in to
339 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
342 * The name of the file to insert
344 * The current edition
345 * @param containerFiles
346 * The container definitions
347 * @return A file entry for the given file
349 private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
350 FileEntry fileEntry = null;
351 FileOption fileOption = project.getFileOption(filename);
352 if (filename.startsWith("/container/:")) {
353 String containerName = filename.substring("/container/:".length());
355 long[] containerLength = new long[1];
356 InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
357 fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
358 } catch (IOException ioe1) {
359 /* ignore, null is returned. */
362 if (fileOption.isInsert()) {
364 long[] fileLength = new long[1];
365 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
366 fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
367 } catch (IOException ioe1) {
368 /* ignore, null is returned. */
371 if (fileOption.isInsertRedirect()) {
372 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
380 * Creates container definitions.
383 * The list of all files
385 * The list of all containers
386 * @param containerFiles
387 * Empty map that will be filled with container definitions
389 private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
390 for (String filename : new ArrayList<String>(files)) {
391 FileOption fileOption = project.getFileOption(filename);
392 String containerName = fileOption.getContainer();
393 if (!containerName.equals("")) {
394 if (!containers.contains(containerName)) {
395 containers.add(containerName);
396 containerFiles.put(containerName, new ArrayList<String>());
397 /* hmm. looks like a hack to me. */
398 files.add("/container/:" + containerName);
400 containerFiles.get(containerName).add(filename);
401 files.remove(filename);
407 * Validates the given project. The project will be checked for any invalid
408 * conditions, such as invalid insert or request keys, missing path names,
409 * missing default file, and so on.
412 * The project to check
413 * @return The encountered warnings and errors
415 public static CheckReport validateProject(Project project) {
416 CheckReport checkReport = new CheckReport();
417 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
418 checkReport.addIssue("error.no-local-path", true);
420 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
421 checkReport.addIssue("error.no-path", true);
423 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
424 checkReport.addIssue("warning.empty-index", false);
426 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
427 if (!indexFile.exists()) {
428 checkReport.addIssue("error.index-missing", true);
431 String indexFile = project.getIndexFile();
432 boolean hasIndexFile = (indexFile != null);
433 if (hasIndexFile && !project.getFileOption(indexFile).getContainer().equals("")) {
434 checkReport.addIssue("warning.container-index", false);
436 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
437 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
438 checkReport.addIssue("warning.index-not-html", false);
440 Map<String, FileOption> fileOptions = project.getFileOptions();
441 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
442 boolean insert = false;
443 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
444 String fileName = fileOptionEntry.getKey();
445 FileOption fileOption = fileOptionEntry.getValue();
446 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
447 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
448 checkReport.addIssue("error.index-not-inserted", true);
450 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
451 checkReport.addIssue("error.no-custom-key", true, fileName);
455 checkReport.addIssue("error.no-files-to-insert", true);
457 Set<String> fileNames = new HashSet<String>();
458 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
459 FileOption fileOption = fileOptionEntry.getValue();
460 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
461 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
464 String fileName = fileOptionEntry.getKey();
465 if (fileOption.hasChangedName()) {
466 fileName = fileOption.getChangedName();
468 logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
469 if (!fileNames.add(fileName)) {
470 checkReport.addIssue("error.duplicate-file", true, fileName);
480 fireProjectInsertStarted();
481 List<String> files = fileScanner.getFiles();
483 /* create connection to node */
484 synchronized (lockObject) {
485 connection = freenetInterface.getConnection("project-insert-" + random + counter++);
487 connection.setTempDirectory(tempDirectory);
488 boolean connected = false;
489 Throwable cause = null;
491 connected = connection.connect();
492 } catch (IOException e1) {
496 if (!connected || cancelled) {
497 fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
501 Client client = new Client(connection);
503 /* create containers */
504 final List<String> containers = new ArrayList<String>();
505 final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
506 createContainers(files, containers, containerFiles);
509 int edition = project.getEdition();
510 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
511 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
512 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
513 putDir.setDefaultName(project.getIndexFile());
515 putDir.setVerbosity(Verbosity.ALL);
516 putDir.setMaxRetries(-1);
517 putDir.setEarlyEncode(false);
518 for (String filename : files) {
519 FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
520 if (fileEntry != null) {
522 putDir.addFileEntry(fileEntry);
523 } catch (IOException ioe1) {
524 fireProjectInsertFinished(false, ioe1);
532 client.execute(putDir);
533 } catch (IOException ioe1) {
534 fireProjectInsertFinished(false, ioe1);
538 /* parse progress and success messages */
539 String finalURI = null;
540 boolean firstMessage = true;
541 boolean success = false;
542 boolean finished = false;
543 boolean disconnected = false;
544 while (!finished && !cancelled) {
545 Message message = client.readMessage();
546 finished = (message == null) || (disconnected = client.isDisconnected());
548 fireProjectUploadFinished();
549 firstMessage = false;
551 logger.log(Level.FINE, "Received message: " + message);
553 @SuppressWarnings("null")
554 String messageName = message.getName();
555 if ("URIGenerated".equals(messageName)) {
556 finalURI = message.get("URI");
557 fireProjectURIGenerated(finalURI);
559 if ("SimpleProgress".equals(messageName)) {
560 int total = Integer.parseInt(message.get("Total"));
561 int succeeded = Integer.parseInt(message.get("Succeeded"));
562 int fatal = Integer.parseInt(message.get("FatallyFailed"));
563 int failed = Integer.parseInt(message.get("Failed"));
564 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
565 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
567 success = "PutSuccessful".equals(messageName);
568 finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
572 /* post-insert work */
574 @SuppressWarnings("null")
575 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
576 int newEdition = Integer.parseInt(editionPart);
577 project.setEdition(newEdition);
578 project.setLastInsertionTime(System.currentTimeMillis());
580 fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
584 // INTERFACE FileScannerListener
590 public void fileScannerFinished(FileScanner fileScanner) {
591 if (!fileScanner.isError()) {
592 new Thread(this).start();
594 fireProjectInsertFinished(false, null);
596 fileScanner.removeFileScannerListener(this);
600 * Container class that collects all warnings and errors that occured during
601 * {@link ProjectInserter#validateProject(Project) project validation}.
603 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
605 public static class CheckReport implements Iterable<Issue> {
607 /** The issures that occured. */
608 private final List<Issue> issues = new ArrayList<Issue>();
616 public void addIssue(Issue issue) {
621 * Creates an {@link Issue} from the given error key and fatality flag
622 * and {@link #addIssue(Issue) adds} it.
627 * {@code true} if the error is fatal, {@code false} if only
628 * a warning should be generated
630 * Any additional parameters
632 public void addIssue(String errorKey, boolean fatal, String... parameters) {
633 addIssue(new Issue(errorKey, fatal, parameters));
639 public Iterator<Issue> iterator() {
640 return issues.iterator();
644 * Returns whether this check report does not contain any errors.
646 * @return {@code true} if this check report does not contain any
647 * errors, {@code false} if this check report does contain
650 public boolean isEmpty() {
651 return issues.isEmpty();
655 * Returns the number of issues in this check report.
657 * @return The number of issues
660 return issues.size();
666 * Container class for a single issue. An issue contains an error key
667 * that describes the error, and a fatality flag that determines whether
668 * the insert has to be aborted (if the flag is {@code true}) or if it
669 * can still be performed and only a warning should be generated (if the
670 * flag is {@code false}).
672 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
675 public static class Issue {
677 /** The error key. */
678 private final String errorKey;
680 /** The fatality flag. */
681 private final boolean fatal;
683 /** Additional parameters. */
684 private String[] parameters;
687 * Creates a new issue.
694 * Any additional parameters
696 protected Issue(String errorKey, boolean fatal, String... parameters) {
697 this.errorKey = errorKey;
699 this.parameters = parameters;
703 * Returns the key of the encountered error.
705 * @return The error key
707 public String getErrorKey() {
712 * Returns whether the issue is fatal and the insert has to be
713 * aborted. Otherwise only a warning should be shown.
715 * @return {@code true} if the insert needs to be aborted, {@code
718 public boolean isFatal() {
723 * Returns any additional parameters.
725 * @return The additional parameters
727 public String[] getParameters() {