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.logging.Level;
34 import java.util.logging.Logger;
35 import java.util.zip.ZipEntry;
36 import java.util.zip.ZipOutputStream;
38 import de.todesbaum.jsite.gui.FileScanner;
39 import de.todesbaum.jsite.gui.FileScannerListener;
40 import de.todesbaum.util.freenet.fcp2.Client;
41 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
42 import de.todesbaum.util.freenet.fcp2.Connection;
43 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
44 import de.todesbaum.util.freenet.fcp2.FileEntry;
45 import de.todesbaum.util.freenet.fcp2.Message;
46 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
47 import de.todesbaum.util.freenet.fcp2.Verbosity;
48 import de.todesbaum.util.io.Closer;
49 import de.todesbaum.util.io.ReplacingOutputStream;
50 import de.todesbaum.util.io.StreamCopier;
53 * Manages project inserts.
55 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
57 public class ProjectInserter implements FileScannerListener, Runnable {
60 private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
62 /** Random number for FCP instances. */
63 private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
65 /** Counter for FCP connection identifier. */
66 private static int counter = 0;
68 /** The list of insert listeners. */
69 private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
71 /** The freenet interface. */
72 protected Freenet7Interface freenetInterface;
74 /** The project to insert. */
75 protected Project project;
77 /** The file scanner. */
78 private FileScanner fileScanner;
80 /** Object used for synchronization. */
81 protected final Object lockObject = new Object();
84 * Adds a listener to the list of registered listeners.
86 * @param insertListener
89 public void addInsertListener(InsertListener insertListener) {
90 insertListeners.add(insertListener);
94 * Removes a listener from the list of registered listeners.
96 * @param insertListener
97 * The listener to remove
99 public void removeInsertListener(InsertListener insertListener) {
100 insertListeners.remove(insertListener);
104 * Notifies all listeners that the project insert has started.
106 * @see InsertListener#projectInsertStarted(Project)
108 protected void fireProjectInsertStarted() {
109 for (InsertListener insertListener : insertListeners) {
110 insertListener.projectInsertStarted(project);
115 * Notifies all listeners that the insert has generated a URI.
117 * @see InsertListener#projectURIGenerated(Project, String)
121 protected void fireProjectURIGenerated(String uri) {
122 for (InsertListener insertListener : insertListeners) {
123 insertListener.projectURIGenerated(project, uri);
128 * Notifies all listeners that the insert has made some progress.
130 * @see InsertListener#projectUploadFinished(Project)
132 protected void fireProjectUploadFinished() {
133 for (InsertListener insertListener : insertListeners) {
134 insertListener.projectUploadFinished(project);
139 * Notifies all listeners that the insert has made some progress.
141 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
144 * The number of succeeded blocks
146 * The number of failed blocks
148 * The number of fatally failed blocks
150 * The total number of blocks
152 * <code>true</code> if the total number of blocks has already
153 * been finalized, <code>false</code> otherwise
155 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
156 for (InsertListener insertListener : insertListeners) {
157 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
162 * Notifies all listeners the project insert has finished.
164 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
166 * <code>true</code> if the project was inserted successfully,
167 * <code>false</code> if it failed
169 * The cause of the failure, if any
171 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
172 for (InsertListener insertListener : insertListeners) {
173 insertListener.projectInsertFinished(project, success, cause);
178 * Sets the project to insert.
181 * The project to insert
183 public void setProject(Project project) {
184 this.project = project;
188 * Sets the freenet interface to use.
190 * @param freenetInterface
191 * The freenet interface to use
193 public void setFreenetInterface(Freenet7Interface freenetInterface) {
194 this.freenetInterface = freenetInterface;
200 public void start() {
201 fileScanner = new FileScanner(project);
202 fileScanner.addFileScannerListener(this);
203 new Thread(fileScanner).start();
207 * Creates an input stream that delivers the given file, replacing edition
208 * tokens in the file’s content, if necessary.
211 * The name of the file
215 * The current edition
217 * An array containing a single long which is used to
218 * <em>return</em> the final length of the file, after all
220 * @return The input stream for the file
221 * @throws IOException
222 * if an I/O error occurs
224 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
225 File file = new File(project.getLocalPath(), filename);
226 length[0] = file.length();
227 if (!fileOption.getReplaceEdition()) {
228 return new FileInputStream(file);
230 ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
231 ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
232 FileInputStream fileInput = new FileInputStream(file);
234 outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
235 outputStream.addReplacement("$[URI]", project.getFinalRequestURI(0));
236 for (int index = 1; index <= fileOption.getEditionRange(); index++) {
237 outputStream.addReplacement("$[URI+" + index + "]", project.getFinalRequestURI(index));
238 outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
240 StreamCopier.copy(fileInput, outputStream, length[0]);
242 Closer.close(fileInput);
243 Closer.close(outputStream);
244 Closer.close(filteredByteOutputStream);
246 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
247 length[0] = filteredBytes.length;
248 return new ByteArrayInputStream(filteredBytes);
252 * Creates an input stream for a container.
254 * @param containerFiles
255 * All container definitions
256 * @param containerName
257 * The name of the container to create
259 * The current edition
260 * @param containerLength
261 * An array containing a single long which is used to
262 * <em>return</em> the final length of the container stream,
263 * after all replacements
264 * @return The input stream for the container
265 * @throws IOException
266 * if an I/O error occurs
268 private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
269 File tempFile = File.createTempFile("jsite", ".zip");
270 tempFile.deleteOnExit();
271 FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
272 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
274 for (String filename : containerFiles.get(containerName)) {
275 File dataFile = new File(project.getLocalPath(), filename);
276 if (dataFile.exists()) {
277 ZipEntry zipEntry = new ZipEntry(filename);
278 long[] fileLength = new long[1];
279 InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
281 zipOutputStream.putNextEntry(zipEntry);
282 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
284 zipOutputStream.closeEntry();
285 wrappedInputStream.close();
290 zipOutputStream.closeEntry();
291 Closer.close(zipOutputStream);
292 Closer.close(fileOutputStream);
295 containerLength[0] = tempFile.length();
296 return new FileInputStream(tempFile);
300 * Creates a file entry suitable for handing in to
301 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
304 * The name of the file to insert
306 * The current edition
307 * @param containerFiles
308 * The container definitions
309 * @return A file entry for the given file
311 private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
312 FileEntry fileEntry = null;
313 FileOption fileOption = project.getFileOption(filename);
314 if (filename.startsWith("/container/:")) {
315 String containerName = filename.substring("/container/:".length());
317 long[] containerLength = new long[1];
318 InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
319 fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
320 } catch (IOException ioe1) {
321 /* ignore, null is returned. */
324 if (fileOption.isInsert()) {
326 long[] fileLength = new long[1];
327 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
328 fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
329 } catch (IOException ioe1) {
330 /* ignore, null is returned. */
333 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
340 * Creates container definitions.
343 * The list of all files
345 * The list of all containers
346 * @param containerFiles
347 * Empty map that will be filled with container definitions
349 private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
350 for (String filename : new ArrayList<String>(files)) {
351 FileOption fileOption = project.getFileOption(filename);
352 String containerName = fileOption.getContainer();
353 if (!containerName.equals("")) {
354 if (!containers.contains(containerName)) {
355 containers.add(containerName);
356 containerFiles.put(containerName, new ArrayList<String>());
357 /* hmm. looks like a hack to me. */
358 files.add("/container/:" + containerName);
360 containerFiles.get(containerName).add(filename);
361 files.remove(filename);
370 fireProjectInsertStarted();
371 List<String> files = fileScanner.getFiles();
373 /* create connection to node */
374 Connection connection = freenetInterface.getConnection("project-insert-" + random + counter++);
375 boolean connected = false;
376 Throwable cause = null;
378 connected = connection.connect();
379 } catch (IOException e1) {
384 fireProjectInsertFinished(false, cause);
388 Client client = new Client(connection);
390 /* create containers */
391 final List<String> containers = new ArrayList<String>();
392 final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
393 createContainers(files, containers, containerFiles);
396 int edition = project.getEdition();
397 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
398 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI);
399 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
400 putDir.setDefaultName(project.getIndexFile());
402 putDir.setVerbosity(Verbosity.ALL);
403 putDir.setMaxRetries(-1);
404 for (String filename : files) {
405 FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
406 if (fileEntry != null) {
407 putDir.addFileEntry(fileEntry);
413 client.execute(putDir);
414 } catch (IOException ioe1) {
415 fireProjectInsertFinished(false, ioe1);
419 /* parse progress and success messages */
420 String finalURI = null;
421 boolean firstMessage = true;
422 boolean success = false;
423 boolean finished = false;
424 boolean disconnected = false;
426 Message message = client.readMessage();
427 finished = (message == null) || (disconnected = client.isDisconnected());
429 fireProjectUploadFinished();
430 firstMessage = false;
432 logger.log(Level.FINE, "Received message: " + message);
434 @SuppressWarnings("null")
435 String messageName = message.getName();
436 if ("URIGenerated".equals(messageName)) {
437 finalURI = message.get("URI");
438 fireProjectURIGenerated(finalURI);
440 if ("SimpleProgress".equals(messageName)) {
441 int total = Integer.parseInt(message.get("Total"));
442 int succeeded = Integer.parseInt(message.get("Succeeded"));
443 int fatal = Integer.parseInt(message.get("FatallyFailed"));
444 int failed = Integer.parseInt(message.get("Failed"));
445 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
446 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
448 success = "PutSuccessful".equals(messageName);
449 finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
453 /* post-insert work */
454 fireProjectInsertFinished(success, disconnected ? new IOException("Connection terminated") : null);
456 @SuppressWarnings("null")
457 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
458 int newEdition = Integer.parseInt(editionPart);
459 project.setEdition(newEdition);
460 project.setLastInsertionTime(System.currentTimeMillis());
465 // INTERFACE FileScannerListener
471 public void fileScannerFinished(FileScanner fileScanner) {
472 if (!fileScanner.isError()) {
473 new Thread(this).start();
475 fireProjectInsertFinished(false, null);
477 fileScanner.removeFileScannerListener(this);