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.ReplacingOutputStream;
47 import de.todesbaum.util.io.StreamCopier;
50 * @author David Roden <droden@gmail.com>
51 * @version $Id: ProjectInserter.java 486 2006-04-27 10:58:34Z bombe $
53 public class ProjectInserter implements FileScannerListener, Runnable {
55 private static int counter = 0;
56 private boolean debug = false;
57 private List<InsertListener> insertListeners = new ArrayList<InsertListener>();
58 protected Freenet7Interface freenetInterface;
59 protected Project project;
60 private FileScanner fileScanner;
61 protected final Object lockObject = new Object();
62 private int maxRetries = 99999;
64 public void addInsertListener(InsertListener insertListener) {
65 insertListeners.add(insertListener);
68 public void removeInsertListener(InsertListener insertListener) {
69 insertListeners.remove(insertListener);
72 protected void fireProjectInsertStarted() {
73 for (InsertListener insertListener: insertListeners) {
74 insertListener.projectInsertStarted(project);
78 protected void fireProjectInsertProgress(int succeeded, int failed, int fatal, int total, boolean finalized) {
79 for (InsertListener insertListener: insertListeners) {
80 insertListener.projectInsertProgress(project, succeeded, failed, fatal, total, finalized);
84 protected void fireProjectInsertFinished(boolean success, Throwable cause) {
85 for (InsertListener insertListener: insertListeners) {
86 insertListener.projectInsertFinished(project, success, cause);
94 public void setDebug(boolean debug) {
100 * The project to set.
102 public void setProject(Project project) {
103 this.project = project;
107 * @param freenetInterface
108 * The freenetInterface to set.
110 public void setFreenetInterface(Freenet7Interface freenetInterface) {
111 this.freenetInterface = freenetInterface;
116 * The maxRetries to set.
118 public void setMaxRetries(int maxRetries) {
119 this.maxRetries = maxRetries;
122 public void start() {
123 fileScanner = new FileScanner(project);
124 fileScanner.addFileScannerListener(this);
125 new Thread(fileScanner).start();
128 private InputStream createFileInputStream(String filename, FileOption fileOption, int edition, long[] length) throws IOException {
129 File file = new File(project.getLocalPath(), filename);
130 length[0] = file.length();
131 if (!fileOption.getReplaceEdition()) {
132 return new FileInputStream(file);
134 ByteArrayOutputStream filteredByteOutputStream = new ByteArrayOutputStream(Math.min(Integer.MAX_VALUE, (int) length[0]));
135 ReplacingOutputStream outputStream = new ReplacingOutputStream(filteredByteOutputStream);
136 FileInputStream fileInput = new FileInputStream(file);
137 outputStream.addReplacement("$[CONTAINER]", "/");
138 outputStream.addReplacement("$[EDITION]", String.valueOf(edition));
139 outputStream.addReplacement("$[URI]", project.getFinalURI(0));
140 for (int index = 1; index <= fileOption.getEditionRange(); index++) {
141 outputStream.addReplacement("$[URI+" + index + "]", project.getFinalURI(index));
142 outputStream.addReplacement("$[EDITION+" + index + "]", String.valueOf(edition + index));
144 StreamCopier.copy(fileInput, outputStream, length[0]);
145 outputStream.close();
146 filteredByteOutputStream.close();
147 byte[] filteredBytes = filteredByteOutputStream.toByteArray();
148 length[0] = filteredBytes.length;
149 return new ByteArrayInputStream(filteredBytes);
152 private InputStream createContainerInputStream(Map<String, List<String>> containerFiles, String containerName, int edition, long[] containerLength) throws IOException {
153 File tempFile = File.createTempFile("jsite", ".zip");
154 tempFile.deleteOnExit();
155 FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
156 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
157 for (String filename: containerFiles.get(containerName)) {
158 File dataFile = new File(project.getLocalPath(), filename);
159 if (dataFile.exists()) {
160 ZipEntry zipEntry = new ZipEntry(filename);
161 long[] fileLength = new long[1];
162 InputStream wrappedInputStream = createFileInputStream(filename, project.getFileOption(filename), edition, fileLength);
163 zipOutputStream.putNextEntry(zipEntry);
164 StreamCopier.copy(wrappedInputStream, zipOutputStream, fileLength[0]);
165 zipOutputStream.closeEntry();
166 wrappedInputStream.close();
169 zipOutputStream.closeEntry();
171 /* FIXME - create metadata */
172 // ZipEntry metadataEntry = new ZipEntry("metadata");
173 // zipOutputStream.putNextEntry(metadataEntry);
174 // Metadata zipMetadata = new Metadata();
175 // for (String filename: containerFiles.get(containerName)) {
176 // if (new File(project.getLocalPath(), filename).exists()) {
177 // DocumentMetadata zipEntryMetadata = new DocumentMetadata();
178 // zipEntryMetadata.setName(filename);
179 // zipEntryMetadata.setFormat(project.getFileOption(filename).getMimeType());
180 // zipMetadata.addDocument(zipEntryMetadata);
183 // zipOutputStream.write(zipMetadata.toByteArray());
184 // zipOutputStream.closeEntry();
185 zipOutputStream.close();
187 containerLength[0] = tempFile.length();
188 return new FileInputStream(tempFile);
191 private FileEntry createFileEntry(String filename, int edition, Map<String, List<String>> containerFiles) {
192 FileEntry fileEntry = null;
193 FileOption fileOption = project.getFileOption(filename);
194 if (filename.startsWith("/container/:")) {
195 String containerName = filename.substring("/container/:".length());
197 long[] containerLength = new long[1];
198 InputStream containerInputStream = createContainerInputStream(containerFiles, containerName, edition, containerLength);
199 fileEntry = new DirectFileEntry(containerName + ".zip", "application/zip", containerInputStream, containerLength[0]);
200 } catch (IOException ioe1) {
203 if (fileOption.isInsert()) {
205 long[] fileLength = new long[1];
206 InputStream fileEntryInputStream = createFileInputStream(filename, fileOption, edition, fileLength);
207 fileEntry = new DirectFileEntry(filename, project.getFileOption(filename).getMimeType(), fileEntryInputStream, fileLength[0]);
208 } catch (IOException ioe1) {
211 fileEntry = new RedirectFileEntry(filename, fileOption.getMimeType(), fileOption.getCustomKey());
217 private void createContainers(List<String> files, List<String> containers, Map<String, List<String>> containerFiles) {
218 for (String filename: new ArrayList<String>(files)) {
219 FileOption fileOption = project.getFileOption(filename);
220 String containerName = fileOption.getContainer();
221 if (!containerName.equals("")) {
222 if (!containers.contains(containerName)) {
223 containers.add(containerName);
224 containerFiles.put(containerName, new ArrayList<String>());
225 /* hmm. looks like a hack to me. */
226 files.add("/container/:" + containerName);
228 containerFiles.get(containerName).add(filename);
229 files.remove(filename);
238 fireProjectInsertStarted();
239 List<String> files = fileScanner.getFiles();
241 /* create connection to node */
242 Connection connection = freenetInterface.getConnection("project-insert-" + counter++);
243 boolean connected = false;
244 Throwable cause = null;
246 connected = connection.connect();
247 } catch (IOException e1) {
252 fireProjectInsertFinished(false, cause);
256 Client client = new Client(connection);
258 /* create containers */
259 final List<String> containers = new ArrayList<String>();
260 final Map<String, List<String>> containerFiles = new HashMap<String, List<String>>();
261 createContainers(files, containers, containerFiles);
264 int edition = ((EditionProject) project).getEdition();
265 String dirURI = project.getInsertURI() + project.getPath() + "-" + edition;
266 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter++, dirURI);
267 putDir.setDefaultName(project.getIndexFile());
268 putDir.setVerbosity(Verbosity.ALL);
269 putDir.setMaxRetries(maxRetries);
270 for (String filename: files) {
271 FileEntry fileEntry = createFileEntry(filename, edition, containerFiles);
272 if (fileEntry != null) {
273 putDir.addFileEntry(fileEntry);
279 client.execute(putDir);
280 } catch (IOException ioe1) {
281 fireProjectInsertFinished(false, ioe1);
285 /* parse progress and success messages */
286 boolean success = true;
287 boolean finished = false;
288 boolean disconnected = false;
290 Message message = client.readMessage();
291 finished = (message == null) && (disconnected = client.isDisconnected());
293 System.out.println(message);
296 String messageName = message.getName();
297 if ("SimpleProgress".equals(messageName)) {
298 int total = Integer.parseInt(message.get("Total"));
299 int succeeded = Integer.parseInt(message.get("Succeeded"));
300 int fatal = Integer.parseInt(message.get("FatallyFailed"));
301 int failed = Integer.parseInt(message.get("Failed"));
302 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
303 fireProjectInsertProgress(succeeded, failed, fatal, total, finalized);
305 success = "PutSuccessful".equals(messageName);
306 finished = success || "PutFailed".equals(messageName);
310 /* post-insert work */
311 fireProjectInsertFinished(success, disconnected ? new IOException("Connection terminated") : null);
313 if (project instanceof EditionProject) {
314 ((EditionProject) project).setEdition(edition + 1);
320 // INTERFACE FileScannerListener
326 public void fileScannerFinished(FileScanner fileScanner) {
327 if (!fileScanner.isError()) {
328 new Thread(this).start();
330 fireProjectInsertFinished(false, null);
332 fileScanner.removeFileScannerListener(this);