46cdbd4daba77a7d6ed4860bcf403b0628690b2b
[jSite.git] / src / de / todesbaum / jsite / application / ProjectInserter.java
1 /*
2  * jSite - a tool for uploading websites into Freenet
3  * Copyright (C) 2006 David Roden
4  *
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.
9  *
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.
14  *
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.
18  */
19
20 package de.todesbaum.jsite.application;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.File;
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;
32 import java.util.Map;
33 import java.util.zip.ZipEntry;
34 import java.util.zip.ZipOutputStream;
35
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;
49
50 /**
51  * Manages project inserts.
52  *
53  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
54  */
55 public class ProjectInserter implements FileScannerListener, Runnable {
56
57         /** Random number for FCP instances. */
58         private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
59
60         /** Counter for FCP connection identifier. */
61         private static int counter = 0;
62
63         /** Whether debug mode is set. */
64         private boolean debug = false;
65
66         /** The list of insert listeners. */
67         private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
68
69         /** The freenet interface. */
70         protected Freenet7Interface freenetInterface;
71
72         /** The project to insert. */
73         protected Project project;
74
75         /** The file scanner. */
76         private FileScanner fileScanner;
77
78         /** Object used for synchronization. */
79         protected final Object lockObject = new Object();
80
81         /**
82          * Adds a listener to the list of registered listeners.
83          *
84          * @param insertListener
85          *            The listener to add
86          */
87         public void addInsertListener(InsertListener insertListener) {
88                 insertListeners.add(insertListener);
89         }
90
91         /**
92          * Removes a listener from the list of registered listeners.
93          *
94          * @param insertListener
95          *            The listener to remove
96          */
97         public void removeInsertListener(InsertListener insertListener) {
98                 insertListeners.remove(insertListener);
99         }
100
101         /**
102          * Notifies all listeners that the project insert has started.
103          *
104          * @see InsertListener#projectInsertStarted(Project)
105          */
106         protected void fireProjectInsertStarted() {
107                 for (InsertListener insertListener : insertListeners) {
108                         insertListener.projectInsertStarted(project);
109                 }
110         }
111
112         /**
113          * Notifies all listeners that the insert has generated a URI.
114          *
115          * @see InsertListener#projectURIGenerated(Project, String)
116          * @param uri
117          *            The generated URI
118          */
119         protected void fireProjectURIGenerated(String uri) {
120                 for (InsertListener insertListener : insertListeners) {
121                         insertListener.projectURIGenerated(project, uri);
122                 }
123         }
124
125         /**
126          * Notifies all listeners that the insert has made some progress.
127          *
128          * @see InsertListener#projectUploadFinished(Project)
129          */
130         protected void fireProjectUploadFinished() {
131                 for (InsertListener insertListener : insertListeners) {
132                         insertListener.projectUploadFinished(project);
133                 }
134         }
135
136         /**
137          * Notifies all listeners that the insert has made some progress.
138          *
139          * @see InsertListener#projectInsertProgress(Project, int, int, int, int,
140          *      boolean)
141          * @param succeeded
142          *            The number of succeeded blocks
143          * @param failed
144          *            The number of failed blocks
145          * @param fatal
146          *            The number of fatally failed blocks
147          * @param total
148          *            The total number of blocks
149          * @param finalized
150          *            <code>true</code> if the total number of blocks has already
151          *            been finalized, <code>false</code> otherwise
152          */
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);
156                 }
157         }
158
159         /**
160          * Notifies all listeners the project insert has finished.
161          *
162          * @see InsertListener#projectInsertFinished(Project, boolean, Throwable)
163          * @param success
164          *            <code>true</code> if the project was inserted successfully,
165          *            <code>false</code> if it failed
166          * @param cause
167          *            The cause of the failure, if any
168          */
169         protected void fireProjectInsertFinished(boolean success, Throwable cause) {
170                 for (InsertListener insertListener : insertListeners) {
171                         insertListener.projectInsertFinished(project, success, cause);
172                 }
173         }
174
175         /**
176          * Sets the debug mode.
177          *
178          * @param debug
179          *            <code>true</code> to activate debug mode, <code>false</code>
180          *            to deactivate
181          */
182         public void setDebug(boolean debug) {
183                 this.debug = debug;
184         }
185
186         /**
187          * Sets the project to insert.
188          *
189          * @param project
190          *            The project to insert
191          */
192         public void setProject(Project project) {
193                 this.project = project;
194         }
195
196         /**
197          * Sets the freenet interface to use.
198          *
199          * @param freenetInterface
200          *            The freenet interface to use
201          */
202         public void setFreenetInterface(Freenet7Interface freenetInterface) {
203                 this.freenetInterface = freenetInterface;
204         }
205
206         /**
207          * Starts the insert.
208          */
209         public void start() {
210                 fileScanner = new FileScanner(project);
211                 fileScanner.addFileScannerListener(this);
212                 new Thread(fileScanner).start();
213         }
214
215         /**
216          * Creates an input stream that delivers the given file, replacing edition
217          * tokens in the file’s content, if necessary.
218          *
219          * @param filename
220          *            The name of the file
221          * @param fileOption
222          *            The file options
223          * @param edition
224          *            The current edition
225          * @param length
226          *            An array containing a single long which is used to
227          *            <em>return</em> the final length of the file, after all
228          *            replacements
229          * @return The input stream for the file
230          * @throws IOException
231          *             if an I/O error occurs
232          */
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);
238                 }
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);
242                 try {
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));
248                         }
249                         StreamCopier.copy(fileInput, outputStream, length[0]);
250                 } finally {
251                         Closer.close(fileInput);
252                         Closer.close(outputStream);
253                         Closer.close(filteredByteOutputStream);
254                 }
255                 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
256                 length[0] = filteredBytes.length;
257                 return new ByteArrayInputStream(filteredBytes);
258         }
259
260         /**
261          * Creates an input stream for a container.
262          *
263          * @param containerFiles
264          *            All container definitions
265          * @param containerName
266          *            The name of the container to create
267          * @param edition
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
276          */
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);
282                 try {
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);
289                                         try {
290                                                 zipOutputStream.putNextEntry(zipEntry);
291                                                 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
292                                         } finally {
293                                                 zipOutputStream.closeEntry();
294                                                 wrappedInputStream.close();
295                                         }
296                                 }
297                         }
298                 } finally {
299                         zipOutputStream.closeEntry();
300                         Closer.close(zipOutputStream);
301                         Closer.close(fileOutputStream);
302                 }
303
304                 containerLength[0] = tempFile.length();
305                 return new FileInputStream(tempFile);
306         }
307
308         /**
309          * Creates a file entry suitable for handing in to
310          * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
311          *
312          * @param filename
313          *            The name of the file to insert
314          * @param edition
315          *            The current edition
316          * @param containerFiles
317          *            The container definitions
318          * @return A file entry for the given file
319          */
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());
325                         try {
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. */
331                         }
332                 } else {
333                         if (fileOption.isInsert()) {
334                                 try {
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. */
340                                 }
341                         } else {
342                                 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
343                         }
344                 }
345                 return fileEntry;
346         }
347
348         /**
349          * Creates container definitions.
350          *
351          * @param files
352          *            The list of all files
353          * @param containers
354          *            The list of all containers
355          * @param containerFiles
356          *            Empty map that will be filled with container definitions
357          */
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);
368                                 }
369                                 containerFiles.get(containerName).add(filename);
370                                 files.remove(filename);
371                         }
372                 }
373         }
374
375         /**
376          * {@inheritDoc}
377          */
378         public void run() {
379                 fireProjectInsertStarted();
380                 List<String> files = fileScanner.getFiles();
381
382                 /* create connection to node */
383                 Connection connection = freenetInterface.getConnection("project-insert-" + random + counter++);
384                 boolean connected = false;
385                 Throwable cause = null;
386                 try {
387                         connected = connection.connect();
388                 } catch (IOException e1) {
389                         cause = e1;
390                 }
391
392                 if (!connected) {
393                         fireProjectInsertFinished(false, cause);
394                         return;
395                 }
396
397                 Client client = new Client(connection);
398
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);
403
404                 /* collect files */
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());
410                 }
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);
417                         }
418                 }
419
420                 /* start request */
421                 try {
422                         client.execute(putDir);
423                 } catch (IOException ioe1) {
424                         fireProjectInsertFinished(false, ioe1);
425                         return;
426                 }
427
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;
434                 while (!finished) {
435                         Message message = client.readMessage();
436                         finished = (message == null) || (disconnected = client.isDisconnected());
437                         if (debug) {
438                                 System.out.println(message);
439                         }
440                         if (firstMessage) {
441                                 fireProjectUploadFinished();
442                                 firstMessage = false;
443                         }
444                         if (!finished) {
445                                 @SuppressWarnings("null")
446                                 String messageName = message.getName();
447                                 if ("URIGenerated".equals(messageName)) {
448                                         finalURI = message.get("URI");
449                                         fireProjectURIGenerated(finalURI);
450                                 }
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);
458                                 }
459                                 success = "PutSuccessful".equals(messageName);
460                                 finished = success || "PutFailed".equals(messageName) || messageName.endsWith("Error");
461                         }
462                 }
463
464                 /* post-insert work */
465                 fireProjectInsertFinished(success, disconnected ? new IOException("Connection terminated") : null);
466                 if (success) {
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());
472                 }
473         }
474
475         //
476         // INTERFACE FileScannerListener
477         //
478
479         /**
480          * {@inheritDoc}
481          */
482         public void fileScannerFinished(FileScanner fileScanner) {
483                 if (!fileScanner.isError()) {
484                         new Thread(this).start();
485                 } else {
486                         fireProjectInsertFinished(false, null);
487                 }
488                 fileScanner.removeFileScannerListener(this);
489         }
490
491 }