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.HashMap;
31 import java.util.List;
33 import java.util.zip.ZipEntry;
34 import java.util.zip.ZipOutputStream;
36 import de.todesbaum.jsite.gui.FileScanner;
37 import de.todesbaum.jsite.gui.FileScannerListener;
38 import de.todesbaum.util.freenet.fcp2.Client;
39 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
40 import de.todesbaum.util.freenet.fcp2.Connection;
41 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
42 import de.todesbaum.util.freenet.fcp2.FileEntry;
43 import de.todesbaum.util.freenet.fcp2.Message;
44 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
45 import de.todesbaum.util.freenet.fcp2.Verbosity;
46 import de.todesbaum.util.io.Closer;
47 import de.todesbaum.util.io.ReplacingOutputStream;
48 import de.todesbaum.util.io.StreamCopier;
51 * Manages project inserts.
53 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
55 public class ProjectInserter implements FileScannerListener, Runnable {
57 /** Random number for FCP instances. */
58 private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
60 /** Counter for FCP connection identifier. */
61 private static int counter = 0;
63 /** Whether debug mode is set. */
64 private boolean debug = false;
66 /** The list of insert listeners. */
67 private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
69 /** The freenet interface. */
70 protected Freenet7Interface freenetInterface;
72 /** The project to insert. */
73 protected Project project;
75 /** The file scanner. */
76 private FileScanner fileScanner;
78 /** Object used for synchronization. */
79 protected final Object lockObject = new Object();
82 * Adds a listener to the list of registered listeners.
84 * @param insertListener
87 public void addInsertListener(InsertListener insertListener) {
88 insertListeners.add(insertListener);
92 * Removes a listener from the list of registered listeners.
94 * @param insertListener
95 * The listener to remove
97 public void removeInsertListener(InsertListener insertListener) {
98 insertListeners.remove(insertListener);
102 * Notifies all listeners that the project insert has started.
104 * @see InsertListener#projectInsertStarted(Project)
106 protected void fireProjectInsertStarted() {
107 for (InsertListener insertListener : insertListeners) {
108 insertListener.projectInsertStarted(project);
113 * Notifies all listeners that the insert has generated a URI.
115 * @see InsertListener#projectURIGenerated(Project, String)
119 protected void fireProjectURIGenerated(String uri) {
120 for (InsertListener insertListener : insertListeners) {
121 insertListener.projectURIGenerated(project, uri);
126 * Notifies all listeners that the insert has made some progress.
128 * @see InsertListener#projectUploadFinished(Project)
130 protected void fireProjectUploadFinished() {
131 for (InsertListener insertListener : insertListeners) {
132 insertListener.projectUploadFinished(project);
137 * Notifies all listeners that the insert has made some progress.
139 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
142 * The number of succeeded blocks
144 * The number of failed blocks
146 * The number of fatally failed blocks
148 * The total number of blocks
150 * <code>true</code> if the total number of blocks has already
151 * been finalized, <code>false</code> otherwise
153 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
154 for (InsertListener insertListener : insertListeners) {
155 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
160 * Notifies all listeners the project insert has finished.
162 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
164 * <code>true</code> if the project was inserted successfully,
165 * <code>false</code> if it failed
167 * The cause of the failure, if any
169 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
170 for (InsertListener insertListener : insertListeners) {
171 insertListener.projectInsertFinished(project, success, cause);
176 * Sets the debug mode.
179 * <code>true</code> to activate debug mode, <code>false</code>
182 public void setDebug(boolean debug) {
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;
209 public void start() {
210 fileScanner = new FileScanner(project);
211 fileScanner.addFileScannerListener(this);
212 new Thread(fileScanner).start();
216 * Creates an input stream that delivers the given file, replacing edition
217 * tokens in the file’s content, if necessary.
220 * The name of the file
224 * The current edition
226 * An array containing a single long which is used to
227 * <em>return</em> the final length of the file, after all
229 * @return The input stream for the file
230 * @throws IOException
231 * if an I/O error occurs
233 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
234 File file = new File(project.getLocalPath(), filename);
235 length[0] = file.length();
236 if (!fileOption.getReplaceEdition()) {
237 return new FileInputStream(file);
239 ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
240 ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
241 FileInputStream fileInput = new FileInputStream(file);
243 outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
244 outputStream.addReplacement("$[URI]", project.getFinalRequestURI(0));
245 for (int index = 1; index <= fileOption.getEditionRange(); index++) {
246 outputStream.addReplacement("$[URI+" + index + "]", project.getFinalRequestURI(index));
247 outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
249 StreamCopier.copy(fileInput, outputStream, length[0]);
251 Closer.close(fileInput);
252 Closer.close(outputStream);
253 Closer.close(filteredByteOutputStream);
255 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
256 length[0] = filteredBytes.length;
257 return new ByteArrayInputStream(filteredBytes);
261 * Creates an input stream for a container.
263 * @param containerFiles
264 * All container definitions
265 * @param containerName
266 * The name of the container to create
268 * The current edition
269 * @param containerLength
270 * An array containing a single long which is used to
271 * <em>return</em> the final length of the container stream,
272 * after all replacements
273 * @return The input stream for the container
274 * @throws IOException
275 * if an I/O error occurs
277 private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
278 File tempFile = File.createTempFile("jsite", ".zip");
279 tempFile.deleteOnExit();
280 FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
281 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
283 for (String filename : containerFiles.get(containerName)) {
284 File dataFile = new File(project.getLocalPath(), filename);
285 if (dataFile.exists()) {
286 ZipEntry zipEntry = new ZipEntry(filename);
287 long[] fileLength = new long[1];
288 InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
290 zipOutputStream.putNextEntry(zipEntry);
291 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
293 zipOutputStream.closeEntry();
294 wrappedInputStream.close();
299 zipOutputStream.closeEntry();
300 Closer.close(zipOutputStream);
301 Closer.close(fileOutputStream);
304 containerLength[0] = tempFile.length();
305 return new FileInputStream(tempFile);
309 * Creates a file entry suitable for handing in to
310 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
313 * The name of the file to insert
315 * The current edition
316 * @param containerFiles
317 * The container definitions
318 * @return A file entry for the given file
320 private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
321 FileEntry fileEntry = null;
322 FileOption fileOption = project.getFileOption(filename);
323 if (filename.startsWith("/container/:")) {
324 String containerName = filename.substring("/container/:".length());
326 long[] containerLength = new long[1];
327 InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
328 fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
329 } catch (IOException ioe1) {
330 /* ignore, null is returned. */
333 if (fileOption.isInsert()) {
335 long[] fileLength = new long[1];
336 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
337 fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
338 } catch (IOException ioe1) {
339 /* ignore, null is returned. */
342 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
349 * Creates container definitions.
352 * The list of all files
354 * The list of all containers
355 * @param containerFiles
356 * Empty map that will be filled with container definitions
358 private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
359 for (String filename : new ArrayList<String>(files)) {
360 FileOption fileOption = project.getFileOption(filename);
361 String containerName = fileOption.getContainer();
362 if (!containerName.equals("")) {
363 if (!containers.contains(containerName)) {
364 containers.add(containerName);
365 containerFiles.put(containerName, new ArrayList<String>());
366 /* hmm. looks like a hack to me. */
367 files.add("/container/:" + containerName);
369 containerFiles.get(containerName).add(filename);
370 files.remove(filename);
379 fireProjectInsertStarted();
380 List<String> files = fileScanner.getFiles();
382 /* create connection to node */
383 Connection connection = freenetInterface.getConnection("project-insert-" + random + counter++);
384 boolean connected = false;
385 Throwable cause = null;
387 connected = connection.connect();
388 } catch (IOException e1) {
393 fireProjectInsertFinished(false, cause);
397 Client client = new Client(connection);
399 /* create containers */
400 final List<String> containers = new ArrayList<String>();
401 final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
402 createContainers(files, containers, containerFiles);
405 int edition = project.getEdition();
406 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
407 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI);
408 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
409 putDir.setDefaultName(project.getIndexFile());
411 putDir.setVerbosity(Verbosity.ALL);
412 putDir.setMaxRetries(-1);
413 for (String filename : files) {
414 FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
415 if (fileEntry != null) {
416 putDir.addFileEntry(fileEntry);
422 client.execute(putDir);
423 } catch (IOException ioe1) {
424 fireProjectInsertFinished(false, ioe1);
428 /* parse progress and success messages */
429 String finalURI = null;
430 boolean firstMessage = true;
431 boolean success = false;
432 boolean finished = false;
433 boolean disconnected = false;
435 Message message = client.readMessage();
436 finished = (message == null) || (disconnected = client.isDisconnected());
438 System.out.println(message);
441 fireProjectUploadFinished();
442 firstMessage = false;
445 @SuppressWarnings("null")
446 String messageName = message.getName();
447 if ("URIGenerated".equals(messageName)) {
448 finalURI = message.get("URI");
449 fireProjectURIGenerated(finalURI);
451 if ("SimpleProgress".equals(messageName)) {
452 int total = Integer.parseInt(message.get("Total"));
453 int succeeded = Integer.parseInt(message.get("Succeeded"));
454 int fatal = Integer.parseInt(message.get("FatallyFailed"));
455 int failed = Integer.parseInt(message.get("Failed"));
456 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
457 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
459 success = "PutSuccessful".equals(messageName);
460 finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
464 /* post-insert work */
465 fireProjectInsertFinished(success, disconnected ? new IOException("Connection terminated") : null);
467 @SuppressWarnings("null")
468 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
469 int newEdition = Integer.parseInt(editionPart);
470 project.setEdition(newEdition);
471 project.setLastInsertionTime(System.currentTimeMillis());
476 // INTERFACE FileScannerListener
482 public void fileScannerFinished(FileScanner fileScanner) {
483 if (!fileScanner.isError()) {
484 new Thread(this).start();
486 fireProjectInsertFinished(false, null);
488 fileScanner.removeFileScannerListener(this);