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;
92 * Adds a listener to the list of registered listeners.
94 * @param insertListener
97 public void addInsertListener(InsertListener insertListener) {
98 insertListeners.add(insertListener);
102 * Removes a listener from the list of registered listeners.
104 * @param insertListener
105 * The listener to remove
107 public void removeInsertListener(InsertListener insertListener) {
108 insertListeners.remove(insertListener);
112 * Notifies all listeners that the project insert has started.
114 * @see InsertListener#projectInsertStarted(Project)
116 protected void fireProjectInsertStarted() {
117 for (InsertListener insertListener : insertListeners) {
118 insertListener.projectInsertStarted(project);
123 * Notifies all listeners that the insert has generated a URI.
125 * @see InsertListener#projectURIGenerated(Project, String)
129 protected void fireProjectURIGenerated(String uri) {
130 for (InsertListener insertListener : insertListeners) {
131 insertListener.projectURIGenerated(project, uri);
136 * Notifies all listeners that the insert has made some progress.
138 * @see InsertListener#projectUploadFinished(Project)
140 protected void fireProjectUploadFinished() {
141 for (InsertListener insertListener : insertListeners) {
142 insertListener.projectUploadFinished(project);
147 * Notifies all listeners that the insert has made some progress.
149 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
152 * The number of succeeded blocks
154 * The number of failed blocks
156 * The number of fatally failed blocks
158 * The total number of blocks
160 * <code>true</code> if the total number of blocks has already
161 * been finalized, <code>false</code> otherwise
163 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
164 for (InsertListener insertListener : insertListeners) {
165 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
170 * Notifies all listeners the project insert has finished.
172 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
174 * <code>true</code> if the project was inserted successfully,
175 * <code>false</code> if it failed
177 * The cause of the failure, if any
179 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
180 for (InsertListener insertListener : insertListeners) {
181 insertListener.projectInsertFinished(project, success, cause);
186 * Sets the project to insert.
189 * The project to insert
191 public void setProject(Project project) {
192 this.project = project;
196 * Sets the freenet interface to use.
198 * @param freenetInterface
199 * The freenet interface to use
201 public void setFreenetInterface(Freenet7Interface freenetInterface) {
202 this.freenetInterface = freenetInterface;
206 * Sets the temp directory to use.
208 * @param tempDirectory
209 * The temp directory to use, or {@code null} to use the system
212 public void setTempDirectory(String tempDirectory) {
213 this.tempDirectory = tempDirectory;
219 public void start() {
220 fileScanner = new FileScanner(project);
221 fileScanner.addFileScannerListener(this);
222 new Thread(fileScanner).start();
226 * Creates an input stream that delivers the given file, replacing edition
227 * tokens in the file’s content, if necessary.
230 * The name of the file
234 * The current edition
236 * An array containing a single long which is used to
237 * <em>return</em> the final length of the file, after all
239 * @return The input stream for the file
240 * @throws IOException
241 * if an I/O error occurs
243 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
244 File file = new File(project.getLocalPath(), filename);
245 length[0] = file.length();
246 if (!fileOption.getReplaceEdition()) {
247 return new FileInputStream(file);
249 ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
250 ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
251 FileInputStream fileInput = new FileInputStream(file);
253 outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
254 outputStream.addReplacement("$[URI]", project.getFinalRequestURI(0));
255 for (int index = 1; index <= fileOption.getEditionRange(); index++) {
256 outputStream.addReplacement("$[URI+" + index + "]", project.getFinalRequestURI(index));
257 outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
259 StreamCopier.copy(fileInput, outputStream, length[0]);
261 Closer.close(fileInput);
262 Closer.close(outputStream);
263 Closer.close(filteredByteOutputStream);
265 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
266 length[0] = filteredBytes.length;
267 return new ByteArrayInputStream(filteredBytes);
271 * Creates an input stream for a container.
273 * @param containerFiles
274 * All container definitions
275 * @param containerName
276 * The name of the container to create
278 * The current edition
279 * @param containerLength
280 * An array containing a single long which is used to
281 * <em>return</em> the final length of the container stream,
282 * after all replacements
283 * @return The input stream for the container
284 * @throws IOException
285 * if an I/O error occurs
287 private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
288 File tempFile = File.createTempFile("jsite", ".zip", (tempDirectory == null) ? null : new File(tempDirectory));
289 tempFile.deleteOnExit();
290 FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
291 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
293 for (String filename : containerFiles.get(containerName)) {
294 File dataFile = new File(project.getLocalPath(), filename);
295 if (dataFile.exists()) {
296 ZipEntry zipEntry = new ZipEntry(filename);
297 long[] fileLength = new long[1];
298 InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
300 zipOutputStream.putNextEntry(zipEntry);
301 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
303 zipOutputStream.closeEntry();
304 wrappedInputStream.close();
309 zipOutputStream.closeEntry();
310 Closer.close(zipOutputStream);
311 Closer.close(fileOutputStream);
314 containerLength[0] = tempFile.length();
315 return new FileInputStream(tempFile);
319 * Creates a file entry suitable for handing in to
320 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
323 * The name of the file to insert
325 * The current edition
326 * @param containerFiles
327 * The container definitions
328 * @return A file entry for the given file
330 private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
331 FileEntry fileEntry = null;
332 FileOption fileOption = project.getFileOption(filename);
333 if (filename.startsWith("/container/:")) {
334 String containerName = filename.substring("/container/:".length());
336 long[] containerLength = new long[1];
337 InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
338 fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
339 } catch (IOException ioe1) {
340 /* ignore, null is returned. */
343 if (fileOption.isInsert()) {
345 long[] fileLength = new long[1];
346 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
347 fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
348 } catch (IOException ioe1) {
349 /* ignore, null is returned. */
352 if (fileOption.isInsertRedirect()) {
353 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
361 * Creates container definitions.
364 * The list of all files
366 * The list of all containers
367 * @param containerFiles
368 * Empty map that will be filled with container definitions
370 private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
371 for (String filename : new ArrayList<String>(files)) {
372 FileOption fileOption = project.getFileOption(filename);
373 String containerName = fileOption.getContainer();
374 if (!containerName.equals("")) {
375 if (!containers.contains(containerName)) {
376 containers.add(containerName);
377 containerFiles.put(containerName, new ArrayList<String>());
378 /* hmm. looks like a hack to me. */
379 files.add("/container/:" + containerName);
381 containerFiles.get(containerName).add(filename);
382 files.remove(filename);
388 * Validates the given project. The project will be checked for any invalid
389 * conditions, such as invalid insert or request keys, missing path names,
390 * missing default file, and so on.
393 * The project to check
394 * @return The encountered warnings and errors
396 public static CheckReport validateProject(Project project) {
397 CheckReport checkReport = new CheckReport();
398 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
399 checkReport.addIssue("error.no-local-path", true);
401 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
402 checkReport.addIssue("error.no-path", true);
404 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
405 checkReport.addIssue("warning.empty-index", false);
407 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
408 if (!indexFile.exists()) {
409 checkReport.addIssue("error.index-missing", true);
412 String indexFile = project.getIndexFile();
413 boolean hasIndexFile = (indexFile != null);
414 if (hasIndexFile && !project.getFileOption(indexFile).getContainer().equals("")) {
415 checkReport.addIssue("warning.container-index", false);
417 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
418 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
419 checkReport.addIssue("warning.index-not-html", false);
421 Map<String, FileOption> fileOptions = project.getFileOptions();
422 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
423 boolean insert = false;
424 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
425 String fileName = fileOptionEntry.getKey();
426 FileOption fileOption = fileOptionEntry.getValue();
427 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
428 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
429 checkReport.addIssue("error.index-not-inserted", true);
431 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
432 checkReport.addIssue("error.no-custom-key", true, fileName);
436 checkReport.addIssue("error.no-files-to-insert", true);
438 Set<String> fileNames = new HashSet<String>();
439 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
440 FileOption fileOption = fileOptionEntry.getValue();
441 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
442 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
445 String fileName = fileOptionEntry.getKey();
446 if (fileOption.hasChangedName()) {
447 fileName = fileOption.getChangedName();
449 logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
450 if (!fileNames.add(fileName)) {
451 checkReport.addIssue("error.duplicate-file", true, fileName);
461 fireProjectInsertStarted();
462 List<String> files = fileScanner.getFiles();
464 /* create connection to node */
465 Connection connection = freenetInterface.getConnection("project-insert-" + random + counter++);
466 connection.setTempDirectory(tempDirectory);
467 boolean connected = false;
468 Throwable cause = null;
470 connected = connection.connect();
471 } catch (IOException e1) {
476 fireProjectInsertFinished(false, cause);
480 Client client = new Client(connection);
482 /* create containers */
483 final List<String> containers = new ArrayList<String>();
484 final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
485 createContainers(files, containers, containerFiles);
488 int edition = project.getEdition();
489 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
490 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
491 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
492 putDir.setDefaultName(project.getIndexFile());
494 putDir.setVerbosity(Verbosity.ALL);
495 putDir.setMaxRetries(-1);
496 for (String filename : files) {
497 FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
498 if (fileEntry != null) {
500 putDir.addFileEntry(fileEntry);
501 } catch (IOException ioe1) {
502 fireProjectInsertFinished(false, ioe1);
510 client.execute(putDir);
511 } catch (IOException ioe1) {
512 fireProjectInsertFinished(false, ioe1);
516 /* parse progress and success messages */
517 String finalURI = null;
518 boolean firstMessage = true;
519 boolean success = false;
520 boolean finished = false;
521 boolean disconnected = false;
523 Message message = client.readMessage();
524 finished = (message == null) || (disconnected = client.isDisconnected());
526 fireProjectUploadFinished();
527 firstMessage = false;
529 logger.log(Level.FINE, "Received message: " + message);
531 @SuppressWarnings("null")
532 String messageName = message.getName();
533 if ("URIGenerated".equals(messageName)) {
534 finalURI = message.get("URI");
535 fireProjectURIGenerated(finalURI);
537 if ("SimpleProgress".equals(messageName)) {
538 int total = Integer.parseInt(message.get("Total"));
539 int succeeded = Integer.parseInt(message.get("Succeeded"));
540 int fatal = Integer.parseInt(message.get("FatallyFailed"));
541 int failed = Integer.parseInt(message.get("Failed"));
542 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
543 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
545 success = "PutSuccessful".equals(messageName);
546 finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
550 /* post-insert work */
552 @SuppressWarnings("null")
553 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
554 int newEdition = Integer.parseInt(editionPart);
555 project.setEdition(newEdition);
556 project.setLastInsertionTime(System.currentTimeMillis());
558 fireProjectInsertFinished(success, disconnected ? new IOException("Connection terminated") : null);
562 // INTERFACE FileScannerListener
568 public void fileScannerFinished(FileScanner fileScanner) {
569 if (!fileScanner.isError()) {
570 new Thread(this).start();
572 fireProjectInsertFinished(false, null);
574 fileScanner.removeFileScannerListener(this);
578 * Container class that collects all warnings and errors that occured during
579 * {@link ProjectInserter#validateProject(Project) project validation}.
581 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
583 public static class CheckReport implements Iterable<Issue> {
585 /** The issures that occured. */
586 private final List<Issue> issues = new ArrayList<Issue>();
594 public void addIssue(Issue issue) {
599 * Creates an {@link Issue} from the given error key and fatality flag
600 * and {@link #addIssue(Issue) adds} it.
605 * {@code true} if the error is fatal, {@code false} if only
606 * a warning should be generated
608 * Any additional parameters
610 public void addIssue(String errorKey, boolean fatal, String... parameters) {
611 addIssue(new Issue(errorKey, fatal, parameters));
617 public Iterator<Issue> iterator() {
618 return issues.iterator();
622 * Returns whether this check report does not contain any errors.
624 * @return {@code true} if this check report does not contain any
625 * errors, {@code false} if this check report does contain
628 public boolean isEmpty() {
629 return issues.isEmpty();
633 * Returns the number of issues in this check report.
635 * @return The number of issues
638 return issues.size();
644 * Container class for a single issue. An issue contains an error key
645 * that describes the error, and a fatality flag that determines whether
646 * the insert has to be aborted (if the flag is {@code true}) or if it
647 * can still be performed and only a warning should be generated (if the
648 * flag is {@code false}).
650 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
653 public static class Issue {
655 /** The error key. */
656 private final String errorKey;
658 /** The fatality flag. */
659 private final boolean fatal;
661 /** Additional parameters. */
662 private String[] parameters;
665 * Creates a new issue.
672 * Any additional parameters
674 protected Issue(String errorKey, boolean fatal, String... parameters) {
675 this.errorKey = errorKey;
677 this.parameters = parameters;
681 * Returns the key of the encountered error.
683 * @return The error key
685 public String getErrorKey() {
690 * Returns whether the issue is fatal and the insert has to be
691 * aborted. Otherwise only a warning should be shown.
693 * @return {@code true} if the insert needs to be aborted, {@code
696 public boolean isFatal() {
701 * Returns any additional parameters.
703 * @return The additional parameters
705 public String[] getParameters() {