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 /** Counter for FCP connection identifier. */
58 private static int counter = 0;
60 /** Whether debug mode is set. */
61 private boolean debug = false;
63 /** The list of insert listeners. */
64 private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
66 /** The freenet interface. */
67 protected Freenet7Interface freenetInterface;
69 /** The project to insert. */
70 protected Project project;
72 /** The file scanner. */
73 private FileScanner fileScanner;
75 /** Object used for synchronization. */
76 protected final Object lockObject = new Object();
79 * Adds a listener to the list of registered listeners.
81 * @param insertListener
84 public void addInsertListener(InsertListener insertListener) {
85 insertListeners.add(insertListener);
89 * Removes a listener from the list of registered listeners.
91 * @param insertListener
92 * The listener to remove
94 public void removeInsertListener(InsertListener insertListener) {
95 insertListeners.remove(insertListener);
99 * Notifies all listeners that the project insert has started.
101 * @see InsertListener#projectInsertStarted(Project)
103 protected void fireProjectInsertStarted() {
104 for (InsertListener insertListener : insertListeners) {
105 insertListener.projectInsertStarted(project);
110 * Notifies all listeners that the insert has generated a URI.
112 * @see InsertListener#projectURIGenerated(Project, String)
116 protected void fireProjectURIGenerated(String uri) {
117 for (InsertListener insertListener : insertListeners) {
118 insertListener.projectURIGenerated(project, uri);
123 * Notifies all listeners that the insert has made some progress.
125 * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
128 * The number of succeeded blocks
130 * The number of failed blocks
132 * The number of fatally failed blocks
134 * The total number of blocks
136 * <code>true</code> if the total number of blocks has already
137 * been finalized, <code>false</code> otherwise
139 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
140 for (InsertListener insertListener : insertListeners) {
141 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
146 * Notifies all listeners the project insert has finished.
148 * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
150 * <code>true</code> if the project was inserted successfully,
151 * <code>false</code> if it failed
153 * The cause of the failure, if any
155 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
156 for (InsertListener insertListener : insertListeners) {
157 insertListener.projectInsertFinished(project, success, cause);
162 * Sets the debug mode.
165 * <code>true</code> to activate debug mode, <code>false</code>
168 public void setDebug(boolean debug) {
173 * Sets the project to insert.
176 * The project to insert
178 public void setProject(Project project) {
179 this.project = project;
183 * Sets the freenet interface to use.
185 * @param freenetInterface
186 * The freenet interface to use
188 public void setFreenetInterface(Freenet7Interface freenetInterface) {
189 this.freenetInterface = freenetInterface;
195 public void start() {
196 fileScanner = new FileScanner(project);
197 fileScanner.addFileScannerListener(this);
198 new Thread(fileScanner).start();
202 * Creates an input stream that delivers the given file, replacing edition
203 * tokens in the file’s content, if necessary.
206 * The name of the file
210 * The current edition
212 * An array containing a single long which is used to
213 * <em>return</em> the final length of the file, after all
215 * @return The input stream for the file
216 * @throws IOException
217 * if an I/O error occurs
219 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
220 File file = new File(project.getLocalPath(), filename);
221 length[0] = file.length();
222 if (!fileOption.getReplaceEdition()) {
223 return new FileInputStream(file);
225 ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
226 ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
227 FileInputStream fileInput = new FileInputStream(file);
229 outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
230 outputStream.addReplacement("$[URI]", project.getFinalRequestURI(0));
231 for (int index = 1; index <= fileOption.getEditionRange(); index++) {
232 outputStream.addReplacement("$[URI+" + index + "]", project.getFinalRequestURI(index));
233 outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
235 StreamCopier.copy(fileInput, outputStream, length[0]);
237 Closer.close(fileInput);
238 Closer.close(outputStream);
239 Closer.close(filteredByteOutputStream);
241 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
242 length[0] = filteredBytes.length;
243 return new ByteArrayInputStream(filteredBytes);
247 * Creates an input stream for a container.
249 * @param containerFiles
250 * All container definitions
251 * @param containerName
252 * The name of the container to create
254 * The current edition
255 * @param containerLength
256 * An array containing a single long which is used to
257 * <em>return</em> the final length of the container stream,
258 * after all replacements
259 * @return The input stream for the container
260 * @throws IOException
261 * if an I/O error occurs
263 private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
264 File tempFile = File.createTempFile("jsite", ".zip");
265 tempFile.deleteOnExit();
266 FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
267 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
269 for (String filename : containerFiles.get(containerName)) {
270 File dataFile = new File(project.getLocalPath(), filename);
271 if (dataFile.exists()) {
272 ZipEntry zipEntry = new ZipEntry(filename);
273 long[] fileLength = new long[1];
274 InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
276 zipOutputStream.putNextEntry(zipEntry);
277 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
279 zipOutputStream.closeEntry();
280 wrappedInputStream.close();
285 zipOutputStream.closeEntry();
286 Closer.close(zipOutputStream);
287 Closer.close(fileOutputStream);
290 containerLength[0] = tempFile.length();
291 return new FileInputStream(tempFile);
295 * Creates a file entry suitable for handing in to
296 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
299 * The name of the file to insert
301 * The current edition
302 * @param containerFiles
303 * The container definitions
304 * @return A file entry for the given file
306 private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
307 FileEntry fileEntry = null;
308 FileOption fileOption = project.getFileOption(filename);
309 if (filename.startsWith("/container/:")) {
310 String containerName = filename.substring("/container/:".length());
312 long[] containerLength = new long[1];
313 InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
314 fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
315 } catch (IOException ioe1) {
316 /* ignore, null is returned. */
319 if (fileOption.isInsert()) {
321 long[] fileLength = new long[1];
322 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
323 fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
324 } catch (IOException ioe1) {
325 /* ignore, null is returned. */
328 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
335 * Creates container definitions.
338 * The list of all files
340 * The list of all containers
341 * @param containerFiles
342 * Empty map that will be filled with container definitions
344 private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
345 for (String filename : new ArrayList<String>(files)) {
346 FileOption fileOption = project.getFileOption(filename);
347 String containerName = fileOption.getContainer();
348 if (!containerName.equals("")) {
349 if (!containers.contains(containerName)) {
350 containers.add(containerName);
351 containerFiles.put(containerName, new ArrayList<String>());
352 /* hmm. looks like a hack to me. */
353 files.add("/container/:" + containerName);
355 containerFiles.get(containerName).add(filename);
356 files.remove(filename);
365 fireProjectInsertStarted();
366 List<String> files = fileScanner.getFiles();
368 /* create connection to node */
369 Connection connection = freenetInterface.getConnection("project-insert-" + counter++);
370 boolean connected = false;
371 Throwable cause = null;
373 connected = connection.connect();
374 } catch (IOException e1) {
379 fireProjectInsertFinished(false, cause);
383 Client client = new Client(connection);
385 /* create containers */
386 final List<String> containers = new ArrayList<String>();
387 final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
388 createContainers(files, containers, containerFiles);
391 int edition = project.getEdition();
392 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
393 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI);
394 putDir.setDefaultName(project.getIndexFile());
395 putDir.setVerbosity(Verbosity.ALL);
396 putDir.setMaxRetries(-1);
397 for (String filename : files) {
398 FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
399 if (fileEntry != null) {
400 putDir.addFileEntry(fileEntry);
406 client.execute(putDir);
407 } catch (IOException ioe1) {
408 fireProjectInsertFinished(false, ioe1);
412 /* parse progress and success messages */
413 String finalURI = null;
414 boolean success = false;
415 boolean finished = false;
416 boolean disconnected = false;
418 Message message = client.readMessage();
419 finished = (message == null) || (disconnected = client.isDisconnected());
421 System.out.println(message);
424 String messageName = message.getName();
425 if ("URIGenerated".equals(messageName)) {
426 finalURI = message.get("URI");
427 fireProjectURIGenerated(finalURI);
429 if ("SimpleProgress".equals(messageName)) {
430 int total = Integer.parseInt(message.get("Total"));
431 int succeeded = Integer.parseInt(message.get("Succeeded"));
432 int fatal = Integer.parseInt(message.get("FatallyFailed"));
433 int failed = Integer.parseInt(message.get("Failed"));
434 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
435 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
437 success = "PutSuccessful".equals(messageName);
438 finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
442 /* post-insert work */
443 fireProjectInsertFinished(success, disconnected ? new IOException("Connection terminated") : null);
445 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
446 int newEdition = Integer.parseInt(editionPart);
447 project.setEdition(newEdition);
448 project.setLastInsertionTime(System.currentTimeMillis());
453 // INTERFACE FileScannerListener
459 public void fileScannerFinished(FileScanner fileScanner) {
460 if (!fileScanner.isError()) {
461 new Thread(this).start();
463 fireProjectInsertFinished(false, null);
465 fileScanner.removeFileScannerListener(this);