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.application.ProjectInserter.CheckReport.Issue;
44 import de.todesbaum.jsite.gui.FileScanner;
45 import de.todesbaum.jsite.gui.FileScannerListener;
46 import de.todesbaum.util.freenet.fcp2.Client;
47 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
48 import de.todesbaum.util.freenet.fcp2.Connection;
49 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
50 import de.todesbaum.util.freenet.fcp2.FileEntry;
51 import de.todesbaum.util.freenet.fcp2.Message;
52 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
53 import de.todesbaum.util.freenet.fcp2.Verbosity;
54 import de.todesbaum.util.io.Closer;
55 import de.todesbaum.util.io.ReplacingOutputStream;
56 import de.todesbaum.util.io.StreamCopier;
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;
93 * Adds a listener to the list of registered listeners.
95 * @param insertListener
98 public void addInsertListener(InsertListener insertListener) {
99 insertListeners.add(insertListener);
103 * Removes a listener from the list of registered listeners.
105 * @param insertListener
106 * The listener to remove
108 public void removeInsertListener(InsertListener insertListener) {
109 insertListeners.remove(insertListener);
113 * Notifies all listeners that the project insert has started.
115 * @see InsertListener#projectInsertStarted(Project)
117 protected void fireProjectInsertStarted() {
118 for (InsertListener insertListener : insertListeners) {
119 insertListener.projectInsertStarted(project);
124 * Notifies all listeners that the insert has generated a URI.
126 * @see InsertListener#projectURIGenerated(Project, String)
130 protected void fireProjectURIGenerated(String uri) {
131 for (InsertListener insertListener : insertListeners) {
132 insertListener.projectURIGenerated(project, uri);
137 * Notifies all listeners that the insert has made some progress.
139 * @see InsertListener#projectUploadFinished(Project)
141 protected void fireProjectUploadFinished() {
142 for (InsertListener insertListener : insertListeners) {
143 insertListener.projectUploadFinished(project);
148 * Notifies all listeners that the insert has made some progress.
150 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
153 * The number of succeeded blocks
155 * The number of failed blocks
157 * The number of fatally failed blocks
159 * The total number of blocks
161 * <code>true</code> if the total number of blocks has already
162 * been finalized, <code>false</code> otherwise
164 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
165 for (InsertListener insertListener : insertListeners) {
166 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
171 * Notifies all listeners the project insert has finished.
173 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
175 * <code>true</code> if the project was inserted successfully,
176 * <code>false</code> if it failed
178 * The cause of the failure, if any
180 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
181 for (InsertListener insertListener : insertListeners) {
182 insertListener.projectInsertFinished(project, success, cause);
187 * Sets the project to insert.
190 * The project to insert
192 public void setProject(Project project) {
193 this.project = project;
197 * Sets the freenet interface to use.
199 * @param freenetInterface
200 * The freenet interface to use
202 public void setFreenetInterface(Freenet7Interface freenetInterface) {
203 this.freenetInterface = freenetInterface;
207 * Sets the temp directory to use.
209 * @param tempDirectory
210 * The temp directory to use, or {@code null} to use the system
213 public void setTempDirectory(String tempDirectory) {
214 this.tempDirectory = tempDirectory;
220 public void start() {
221 fileScanner = new FileScanner(project);
222 fileScanner.addFileScannerListener(this);
223 new Thread(fileScanner).start();
227 * Creates an input stream that delivers the given file, replacing edition
228 * tokens in the file’s content, if necessary.
231 * The name of the file
235 * The current edition
237 * An array containing a single long which is used to
238 * <em>return</em> the final length of the file, after all
240 * @return The input stream for the file
241 * @throws IOException
242 * if an I/O error occurs
244 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
245 File file = new File(project.getLocalPath(), filename);
246 length[0] = file.length();
247 if (!fileOption.getReplaceEdition()) {
248 return new FileInputStream(file);
250 ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
251 ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
252 FileInputStream fileInput = new FileInputStream(file);
254 outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
255 outputStream.addReplacement("$[URI]", project.getFinalRequestURI(0));
256 for (int index = 1; index <= fileOption.getEditionRange(); index++) {
257 outputStream.addReplacement("$[URI+" + index + "]", project.getFinalRequestURI(index));
258 outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
260 StreamCopier.copy(fileInput, outputStream, length[0]);
262 Closer.close(fileInput);
263 Closer.close(outputStream);
264 Closer.close(filteredByteOutputStream);
266 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
267 length[0] = filteredBytes.length;
268 return new ByteArrayInputStream(filteredBytes);
272 * Creates an input stream for a container.
274 * @param containerFiles
275 * All container definitions
276 * @param containerName
277 * The name of the container to create
279 * The current edition
280 * @param containerLength
281 * An array containing a single long which is used to
282 * <em>return</em> the final length of the container stream,
283 * after all replacements
284 * @return The input stream for the container
285 * @throws IOException
286 * if an I/O error occurs
288 private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
289 File tempFile = File.createTempFile("jsite", ".zip", (tempDirectory == null) ? null : new File(tempDirectory));
290 tempFile.deleteOnExit();
291 FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
292 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
294 for (String filename : containerFiles.get(containerName)) {
295 File dataFile = new File(project.getLocalPath(), filename);
296 if (dataFile.exists()) {
297 ZipEntry zipEntry = new ZipEntry(filename);
298 long[] fileLength = new long[1];
299 InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
301 zipOutputStream.putNextEntry(zipEntry);
302 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
304 zipOutputStream.closeEntry();
305 wrappedInputStream.close();
310 zipOutputStream.closeEntry();
311 Closer.close(zipOutputStream);
312 Closer.close(fileOutputStream);
315 containerLength[0] = tempFile.length();
316 return new FileInputStream(tempFile);
320 * Creates a file entry suitable for handing in to
321 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
324 * The name of the file to insert
326 * The current edition
327 * @param containerFiles
328 * The container definitions
329 * @return A file entry for the given file
331 private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
332 FileEntry fileEntry = null;
333 FileOption fileOption = project.getFileOption(filename);
334 if (filename.startsWith("/container/:")) {
335 String containerName = filename.substring("/container/:".length());
337 long[] containerLength = new long[1];
338 InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
339 fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
340 } catch (IOException ioe1) {
341 /* ignore, null is returned. */
344 if (fileOption.isInsert()) {
346 long[] fileLength = new long[1];
347 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
348 fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
349 } catch (IOException ioe1) {
350 /* ignore, null is returned. */
353 if (fileOption.isInsertRedirect()) {
354 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
362 * Creates container definitions.
365 * The list of all files
367 * The list of all containers
368 * @param containerFiles
369 * Empty map that will be filled with container definitions
371 private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
372 for (String filename : new ArrayList<String>(files)) {
373 FileOption fileOption = project.getFileOption(filename);
374 String containerName = fileOption.getContainer();
375 if (!containerName.equals("")) {
376 if (!containers.contains(containerName)) {
377 containers.add(containerName);
378 containerFiles.put(containerName, new ArrayList<String>());
379 /* hmm. looks like a hack to me. */
380 files.add("/container/:" + containerName);
382 containerFiles.get(containerName).add(filename);
383 files.remove(filename);
389 * Validates the given project. The project will be checked for any invalid
390 * conditions, such as invalid insert or request keys, missing path names,
391 * missing default file, and so on.
394 * The project to check
395 * @return The encountered warnings and errors
397 public static CheckReport validateProject(Project project) {
398 CheckReport checkReport = new CheckReport();
399 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
400 checkReport.addIssue("error.no-local-path", true);
402 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
403 checkReport.addIssue("error.no-path", true);
405 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
406 checkReport.addIssue("warning.empty-index", false);
408 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
409 if (!indexFile.exists()) {
410 checkReport.addIssue("error.index-missing", true);
413 String indexFile = project.getIndexFile();
414 boolean hasIndexFile = (indexFile != null);
415 if (hasIndexFile && !project.getFileOption(indexFile).getContainer().equals("")) {
416 checkReport.addIssue("warning.container-index", false);
418 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
419 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
420 checkReport.addIssue("warning.index-not-html", false);
422 Map<String, FileOption> fileOptions = project.getFileOptions();
423 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
424 boolean insert = false;
425 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
426 String fileName = fileOptionEntry.getKey();
427 FileOption fileOption = fileOptionEntry.getValue();
428 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
429 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
430 checkReport.addIssue("error.index-not-inserted", true);
432 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
433 checkReport.addIssue("error.no-custom-key", true, fileName);
437 checkReport.addIssue("error.no-files-to-insert", true);
439 Set<String> fileNames = new HashSet<String>();
440 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
441 FileOption fileOption = fileOptionEntry.getValue();
442 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
443 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
446 String fileName = fileOptionEntry.getKey();
447 if (fileOption.hasChangedName()) {
448 fileName = fileOption.getChangedName();
450 logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
451 if (!fileNames.add(fileName)) {
452 checkReport.addIssue("error.duplicate-file", true, fileName);
462 fireProjectInsertStarted();
463 List<String> files = fileScanner.getFiles();
465 /* create connection to node */
466 Connection connection = freenetInterface.getConnection("project-insert-" + random + counter++);
467 connection.setTempDirectory(tempDirectory);
468 boolean connected = false;
469 Throwable cause = null;
471 connected = connection.connect();
472 } catch (IOException e1) {
477 fireProjectInsertFinished(false, cause);
481 Client client = new Client(connection);
483 /* create containers */
484 final List<String> containers = new ArrayList<String>();
485 final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
486 createContainers(files, containers, containerFiles);
489 int edition = project.getEdition();
490 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
491 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
492 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
493 putDir.setDefaultName(project.getIndexFile());
495 putDir.setVerbosity(Verbosity.ALL);
496 putDir.setMaxRetries(-1);
497 for (String filename : files) {
498 FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
499 if (fileEntry != null) {
501 putDir.addFileEntry(fileEntry);
502 } catch (IOException ioe1) {
503 fireProjectInsertFinished(false, ioe1);
511 client.execute(putDir);
512 } catch (IOException ioe1) {
513 fireProjectInsertFinished(false, ioe1);
517 /* parse progress and success messages */
518 String finalURI = null;
519 boolean firstMessage = true;
520 boolean success = false;
521 boolean finished = false;
522 boolean disconnected = false;
524 Message message = client.readMessage();
525 finished = (message == null) || (disconnected = client.isDisconnected());
527 fireProjectUploadFinished();
528 firstMessage = false;
530 logger.log(Level.FINE, "Received message: " + message);
532 @SuppressWarnings("null")
533 String messageName = message.getName();
534 if ("URIGenerated".equals(messageName)) {
535 finalURI = message.get("URI");
536 fireProjectURIGenerated(finalURI);
538 if ("SimpleProgress".equals(messageName)) {
539 int total = Integer.parseInt(message.get("Total"));
540 int succeeded = Integer.parseInt(message.get("Succeeded"));
541 int fatal = Integer.parseInt(message.get("FatallyFailed"));
542 int failed = Integer.parseInt(message.get("Failed"));
543 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
544 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
546 success = "PutSuccessful".equals(messageName);
547 finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
551 /* post-insert work */
553 @SuppressWarnings("null")
554 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
555 int newEdition = Integer.parseInt(editionPart);
556 project.setEdition(newEdition);
557 project.setLastInsertionTime(System.currentTimeMillis());
559 fireProjectInsertFinished(success, disconnected ? new IOException("Connection terminated") : null);
563 // INTERFACE FileScannerListener
569 public void fileScannerFinished(FileScanner fileScanner) {
570 if (!fileScanner.isError()) {
571 new Thread(this).start();
573 fireProjectInsertFinished(false, null);
575 fileScanner.removeFileScannerListener(this);
579 * Container class that collects all warnings and errors that occured during
580 * {@link ProjectInserter#validateProject(Project) project validation}.
582 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
584 public static class CheckReport implements Iterable<Issue> {
586 /** The issures that occured. */
587 private final List<Issue> issues = new ArrayList<Issue>();
595 public void addIssue(Issue issue) {
600 * Creates an {@link Issue} from the given error key and fatality flag
601 * and {@link #addIssue(Issue) adds} it.
606 * {@code true} if the error is fatal, {@code false} if only
607 * a warning should be generated
609 * Any additional parameters
611 public void addIssue(String errorKey, boolean fatal, String... parameters) {
612 addIssue(new Issue(errorKey, fatal, parameters));
618 public Iterator<Issue> iterator() {
619 return issues.iterator();
623 * Returns whether this check report does not contain any errors.
625 * @return {@code true} if this check report does not contain any
626 * errors, {@code false} if this check report does contain
629 public boolean isEmpty() {
630 return issues.isEmpty();
634 * Returns the number of issues in this check report.
636 * @return The number of issues
639 return issues.size();
643 * Container class for a single issue. An issue contains an error key
644 * that describes the error, and a fatality flag that determines whether
645 * the insert has to be aborted (if the flag is {@code true}) or if it
646 * can still be performed and only a warning should be generated (if the
647 * flag is {@code false}).
649 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
652 public static class Issue {
654 /** The error key. */
655 private final String errorKey;
657 /** The fatality flag. */
658 private final boolean fatal;
660 /** Additional parameters. */
661 private String[] parameters;
664 * Creates a new issue.
671 * Any additional parameters
673 protected Issue(String errorKey, boolean fatal, String... parameters) {
674 this.errorKey = errorKey;
676 this.parameters = parameters;
680 * Returns the key of the encountered error.
682 * @return The error key
684 public String getErrorKey() {
689 * Returns whether the issue is fatal and the insert has to be
690 * aborted. Otherwise only a warning should be shown.
692 * @return {@code true} if the insert needs to be aborted, {@code
695 public boolean isFatal() {
700 * Returns any additional parameters.
702 * @return The additional parameters
704 public String[] getParameters() {