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.Connection;
47 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
48 import de.todesbaum.util.freenet.fcp2.FileEntry;
49 import de.todesbaum.util.freenet.fcp2.Message;
50 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
51 import de.todesbaum.util.freenet.fcp2.Verbosity;
52 import de.todesbaum.util.io.Closer;
53 import de.todesbaum.util.io.ReplacingOutputStream;
54 import de.todesbaum.util.io.StreamCopier;
55 import de.todesbaum.util.io.StreamCopier.ProgressListener;
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;
97 /** Progress listener for payload transfers. */
98 private ProgressListener progressListener;
101 * Adds a listener to the list of registered listeners.
103 * @param insertListener
104 * The listener to add
106 public void addInsertListener(InsertListener insertListener) {
107 insertListeners.add(insertListener);
111 * Removes a listener from the list of registered listeners.
113 * @param insertListener
114 * The listener to remove
116 public void removeInsertListener(InsertListener insertListener) {
117 insertListeners.remove(insertListener);
121 * Notifies all listeners that the project insert has started.
123 * @see InsertListener#projectInsertStarted(Project)
125 protected void fireProjectInsertStarted() {
126 for (InsertListener insertListener : insertListeners) {
127 insertListener.projectInsertStarted(project);
132 * Notifies all listeners that the insert has generated a URI.
134 * @see InsertListener#projectURIGenerated(Project, String)
138 protected void fireProjectURIGenerated(String uri) {
139 for (InsertListener insertListener : insertListeners) {
140 insertListener.projectURIGenerated(project, uri);
145 * Notifies all listeners that the insert has made some progress.
147 * @see InsertListener#projectUploadFinished(Project)
149 protected void fireProjectUploadFinished() {
150 for (InsertListener insertListener : insertListeners) {
151 insertListener.projectUploadFinished(project);
156 * Notifies all listeners that the insert has made some progress.
158 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
161 * The number of succeeded blocks
163 * The number of failed blocks
165 * The number of fatally failed blocks
167 * The total number of blocks
169 * <code>true</code> if the total number of blocks has already
170 * been finalized, <code>false</code> otherwise
172 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
173 for (InsertListener insertListener : insertListeners) {
174 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
179 * Notifies all listeners the project insert has finished.
181 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
183 * <code>true</code> if the project was inserted successfully,
184 * <code>false</code> if it failed
186 * The cause of the failure, if any
188 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
189 for (InsertListener insertListener : insertListeners) {
190 insertListener.projectInsertFinished(project, success, cause);
195 * Sets the project to insert.
198 * The project to insert
200 public void setProject(Project project) {
201 this.project = project;
205 * Sets the freenet interface to use.
207 * @param freenetInterface
208 * The freenet interface to use
210 public void setFreenetInterface(Freenet7Interface freenetInterface) {
211 this.freenetInterface = freenetInterface;
215 * Sets the temp directory to use.
217 * @param tempDirectory
218 * The temp directory to use, or {@code null} to use the system
221 public void setTempDirectory(String tempDirectory) {
222 this.tempDirectory = tempDirectory;
228 * @param progressListener
229 * Listener to notify on progress events
231 public void start(ProgressListener progressListener) {
233 this.progressListener = progressListener;
234 fileScanner = new FileScanner(project);
235 fileScanner.addFileScannerListener(this);
236 new Thread(fileScanner).start();
240 * Stops the current insert.
244 synchronized (lockObject) {
245 if (connection != null) {
246 connection.disconnect();
252 * Creates an input stream that delivers the given file, replacing edition
253 * tokens in the file’s content, if necessary.
256 * The name of the file
260 * The current edition
262 * An array containing a single long which is used to
263 * <em>return</em> the final length of the file, after all
265 * @return The input stream for the file
266 * @throws IOException
267 * if an I/O error occurs
269 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
270 File file = new File(project.getLocalPath(), filename);
271 length[0] = file.length();
272 if (!fileOption.getReplaceEdition()) {
273 return new FileInputStream(file);
275 ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
276 ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
277 FileInputStream fileInput = new FileInputStream(file);
279 outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
280 outputStream.addReplacement("$[URI]", project.getFinalRequestURI(0));
281 for (int index = 1; index <= fileOption.getEditionRange(); index++) {
282 outputStream.addReplacement("$[URI+" + index + "]", project.getFinalRequestURI(index));
283 outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
285 StreamCopier.copy(fileInput, outputStream, length[0]);
287 Closer.close(fileInput);
288 Closer.close(outputStream);
289 Closer.close(filteredByteOutputStream);
291 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
292 length[0] = filteredBytes.length;
293 return new ByteArrayInputStream(filteredBytes);
297 * Creates an input stream for a container.
299 * @param containerFiles
300 * All container definitions
301 * @param containerName
302 * The name of the container to create
304 * The current edition
305 * @param containerLength
306 * An array containing a single long which is used to
307 * <em>return</em> the final length of the container stream,
308 * after all replacements
309 * @return The input stream for the container
310 * @throws IOException
311 * if an I/O error occurs
313 private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
314 File tempFile = File.createTempFile("jsite", ".zip", (tempDirectory == null) ? null : new File(tempDirectory));
315 tempFile.deleteOnExit();
316 FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
317 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
319 for (String filename : containerFiles.get(containerName)) {
320 File dataFile = new File(project.getLocalPath(), filename);
321 if (dataFile.exists()) {
322 ZipEntry zipEntry = new ZipEntry(filename);
323 long[] fileLength = new long[1];
324 InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
326 zipOutputStream.putNextEntry(zipEntry);
327 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
329 zipOutputStream.closeEntry();
330 wrappedInputStream.close();
335 zipOutputStream.closeEntry();
336 Closer.close(zipOutputStream);
337 Closer.close(fileOutputStream);
340 containerLength[0] = tempFile.length();
341 return new FileInputStream(tempFile);
345 * Creates a file entry suitable for handing in to
346 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
349 * The name of the file to insert
351 * The current edition
352 * @param containerFiles
353 * The container definitions
354 * @return A file entry for the given file
356 private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
357 FileEntry fileEntry = null;
358 FileOption fileOption = project.getFileOption(filename);
359 if (filename.startsWith("/container/:")) {
360 String containerName = filename.substring("/container/:".length());
362 long[] containerLength = new long[1];
363 InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
364 fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
365 } catch (IOException ioe1) {
366 /* ignore, null is returned. */
369 if (fileOption.isInsert()) {
371 long[] fileLength = new long[1];
372 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
373 fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
374 } catch (IOException ioe1) {
375 /* ignore, null is returned. */
378 if (fileOption.isInsertRedirect()) {
379 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
387 * Creates container definitions.
390 * The list of all files
392 * The list of all containers
393 * @param containerFiles
394 * Empty map that will be filled with container definitions
396 private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
397 for (String filename : new ArrayList<String>(files)) {
398 FileOption fileOption = project.getFileOption(filename);
399 String containerName = fileOption.getContainer();
400 if (!containerName.equals("")) {
401 if (!containers.contains(containerName)) {
402 containers.add(containerName);
403 containerFiles.put(containerName, new ArrayList<String>());
404 /* hmm. looks like a hack to me. */
405 files.add("/container/:" + containerName);
407 containerFiles.get(containerName).add(filename);
408 files.remove(filename);
414 * Validates the given project. The project will be checked for any invalid
415 * conditions, such as invalid insert or request keys, missing path names,
416 * missing default file, and so on.
419 * The project to check
420 * @return The encountered warnings and errors
422 public static CheckReport validateProject(Project project) {
423 CheckReport checkReport = new CheckReport();
424 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
425 checkReport.addIssue("error.no-local-path", true);
427 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
428 checkReport.addIssue("error.no-path", true);
430 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
431 checkReport.addIssue("warning.empty-index", false);
433 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
434 if (!indexFile.exists()) {
435 checkReport.addIssue("error.index-missing", true);
438 String indexFile = project.getIndexFile();
439 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
440 if (hasIndexFile && !project.getFileOption(indexFile).getContainer().equals("")) {
441 checkReport.addIssue("warning.container-index", false);
443 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
444 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
445 checkReport.addIssue("warning.index-not-html", false);
447 Map<String, FileOption> fileOptions = project.getFileOptions();
448 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
449 boolean insert = fileOptionEntries.isEmpty();
450 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
451 String fileName = fileOptionEntry.getKey();
452 FileOption fileOption = fileOptionEntry.getValue();
453 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
454 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
455 checkReport.addIssue("error.index-not-inserted", true);
457 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
458 checkReport.addIssue("error.no-custom-key", true, fileName);
462 checkReport.addIssue("error.no-files-to-insert", true);
464 Set<String> fileNames = new HashSet<String>();
465 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
466 FileOption fileOption = fileOptionEntry.getValue();
467 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
468 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
471 String fileName = fileOptionEntry.getKey();
472 if (fileOption.hasChangedName()) {
473 fileName = fileOption.getChangedName();
475 logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
476 if (!fileNames.add(fileName)) {
477 checkReport.addIssue("error.duplicate-file", true, fileName);
487 fireProjectInsertStarted();
488 List<String> files = fileScanner.getFiles();
490 /* create connection to node */
491 synchronized (lockObject) {
492 connection = freenetInterface.getConnection("project-insert-" + random + counter++);
494 connection.setTempDirectory(tempDirectory);
495 boolean connected = false;
496 Throwable cause = null;
498 connected = connection.connect();
499 } catch (IOException e1) {
503 if (!connected || cancelled) {
504 fireProjectInsertFinished(false, cancelled ? new AbortedException() : cause);
508 Client client = new Client(connection);
510 /* create containers */
511 final List<String> containers = new ArrayList<String>();
512 final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
513 createContainers(files, containers, containerFiles);
516 int edition = project.getEdition();
517 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
518 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI, tempDirectory);
519 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
520 putDir.setDefaultName(project.getIndexFile());
522 putDir.setVerbosity(Verbosity.ALL);
523 putDir.setMaxRetries(-1);
524 putDir.setEarlyEncode(false);
525 for (String filename : files) {
526 FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
527 if (fileEntry != null) {
529 putDir.addFileEntry(fileEntry);
530 } catch (IOException ioe1) {
531 fireProjectInsertFinished(false, ioe1);
539 client.execute(putDir, progressListener);
540 fireProjectUploadFinished();
541 } catch (IOException ioe1) {
542 fireProjectInsertFinished(false, ioe1);
546 /* parse progress and success messages */
547 String finalURI = null;
548 boolean success = false;
549 boolean finished = false;
550 boolean disconnected = false;
551 while (!finished && !cancelled) {
552 Message message = client.readMessage();
553 finished = (message == null) || (disconnected = client.isDisconnected());
554 logger.log(Level.FINE, "Received message: " + message);
556 @SuppressWarnings("null")
557 String messageName = message.getName();
558 if ("URIGenerated".equals(messageName)) {
559 finalURI = message.get("URI");
560 fireProjectURIGenerated(finalURI);
562 if ("SimpleProgress".equals(messageName)) {
563 int total = Integer.parseInt(message.get("Total"));
564 int succeeded = Integer.parseInt(message.get("Succeeded"));
565 int fatal = Integer.parseInt(message.get("FatallyFailed"));
566 int failed = Integer.parseInt(message.get("Failed"));
567 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
568 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
570 success = "PutSuccessful".equals(messageName);
571 finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
575 /* post-insert work */
577 @SuppressWarnings("null")
578 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
579 int newEdition = Integer.parseInt(editionPart);
580 project.setEdition(newEdition);
581 project.setLastInsertionTime(System.currentTimeMillis());
583 fireProjectInsertFinished(success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
587 // INTERFACE FileScannerListener
593 public void fileScannerFinished(FileScanner fileScanner) {
594 if (!fileScanner.isError()) {
595 new Thread(this).start();
597 fireProjectInsertFinished(false, null);
599 fileScanner.removeFileScannerListener(this);
603 * Container class that collects all warnings and errors that occured during
604 * {@link ProjectInserter#validateProject(Project) project validation}.
606 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
608 public static class CheckReport implements Iterable<Issue> {
610 /** The issures that occured. */
611 private final List<Issue> issues = new ArrayList<Issue>();
619 public void addIssue(Issue issue) {
624 * Creates an {@link Issue} from the given error key and fatality flag
625 * and {@link #addIssue(Issue) adds} it.
630 * {@code true} if the error is fatal, {@code false} if only
631 * a warning should be generated
633 * Any additional parameters
635 public void addIssue(String errorKey, boolean fatal, String... parameters) {
636 addIssue(new Issue(errorKey, fatal, parameters));
642 public Iterator<Issue> iterator() {
643 return issues.iterator();
647 * Returns whether this check report does not contain any errors.
649 * @return {@code true} if this check report does not contain any
650 * errors, {@code false} if this check report does contain
653 public boolean isEmpty() {
654 return issues.isEmpty();
658 * Returns the number of issues in this check report.
660 * @return The number of issues
663 return issues.size();
669 * Container class for a single issue. An issue contains an error key
670 * that describes the error, and a fatality flag that determines whether
671 * the insert has to be aborted (if the flag is {@code true}) or if it
672 * can still be performed and only a warning should be generated (if the
673 * flag is {@code false}).
675 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
678 public static class Issue {
680 /** The error key. */
681 private final String errorKey;
683 /** The fatality flag. */
684 private final boolean fatal;
686 /** Additional parameters. */
687 private String[] parameters;
690 * Creates a new issue.
697 * Any additional parameters
699 protected Issue(String errorKey, boolean fatal, String... parameters) {
700 this.errorKey = errorKey;
702 this.parameters = parameters;
706 * Returns the key of the encountered error.
708 * @return The error key
710 public String getErrorKey() {
715 * Returns whether the issue is fatal and the insert has to be
716 * aborted. Otherwise only a warning should be shown.
718 * @return {@code true} if the insert needs to be aborted, {@code
721 public boolean isFatal() {
726 * Returns any additional parameters.
728 * @return The additional parameters
730 public String[] getParameters() {