2 * jSite - ProjectInserter.java - Copyright Ā© 2006ā2014 David Roden
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 package de.todesbaum.jsite.application;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.Map.Entry;
33 import java.util.Optional;
35 import java.util.concurrent.CountDownLatch;
36 import java.util.concurrent.atomic.AtomicInteger;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
40 import net.pterodactylus.util.io.StreamCopier.ProgressListener;
42 import de.todesbaum.jsite.gui.FileScanner;
43 import de.todesbaum.jsite.gui.FileScanner.ScannedFile;
44 import de.todesbaum.jsite.gui.FileScannerListener;
45 import de.todesbaum.util.freenet.fcp2.Client;
46 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
47 import de.todesbaum.util.freenet.fcp2.Connection;
48 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
49 import de.todesbaum.util.freenet.fcp2.FileEntry;
50 import de.todesbaum.util.freenet.fcp2.Message;
51 import de.todesbaum.util.freenet.fcp2.PriorityClass;
52 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
53 import de.todesbaum.util.freenet.fcp2.Verbosity;
56 * Manages project inserts.
58 * @author David āBombeā Roden <bombe@freenetproject.org>
60 public class ProjectInserter implements FileScannerListener, Runnable {
63 private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
65 /** Random number for FCP instances. */
66 private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
68 /** Counter for FCP connection identifier. */
69 private static final AtomicInteger counter = new AtomicInteger();
71 private final ProjectInsertListeners projectInsertListeners = new ProjectInsertListeners();
73 /** The freenet interface. */
74 private Freenet7Interface freenetInterface;
76 /** The project to insert. */
77 private Project project;
79 /** The file scanner. */
80 private FileScanner fileScanner;
82 /** Object used for synchronization. */
83 private final Object lockObject = new Object();
85 /** The temp directory. */
86 private String tempDirectory;
88 /** The current connection. */
89 private Connection connection;
91 /** Whether the insert is cancelled. */
92 private volatile boolean cancelled = false;
94 /** Progress listener for payload transfers. */
95 private ProgressListener progressListener;
97 /** Whether to use āearly encode.ā */
98 private boolean useEarlyEncode;
100 /** The insert priority. */
101 private PriorityClass priority;
104 * Adds a listener to the list of registered listeners.
106 * @param insertListener
107 * The listener to add
109 public void addInsertListener(InsertListener insertListener) {
110 projectInsertListeners.addInsertListener(insertListener);
114 * Sets the project to insert.
117 * The project to insert
119 public void setProject(Project project) {
120 this.project = project;
124 * Sets the freenet interface to use.
126 * @param freenetInterface
127 * The freenet interface to use
129 public void setFreenetInterface(Freenet7Interface freenetInterface) {
130 this.freenetInterface = freenetInterface;
134 * Sets the temp directory to use.
136 * @param tempDirectory
137 * The temp directory to use, or {@code null} to use the system
140 public void setTempDirectory(String tempDirectory) {
141 this.tempDirectory = tempDirectory;
145 * Sets whether to use the āearly encodeā flag for the insert.
147 * @param useEarlyEncode
148 * {@code true} to set the āearly encodeā flag for the insert,
149 * {@code false} otherwise
151 public void setUseEarlyEncode(boolean useEarlyEncode) {
152 this.useEarlyEncode = useEarlyEncode;
156 * Sets the insert priority.
159 * The insert priority
161 public void setPriority(PriorityClass priority) {
162 this.priority = priority;
168 * @param progressListener
169 * Listener to notify on progress events
171 public void start(ProgressListener progressListener) {
173 this.progressListener = progressListener;
174 fileScanner = new FileScanner(project, this);
175 fileScanner.startInBackground();
179 * Stops the current insert.
183 synchronized (lockObject) {
184 if (connection != null) {
185 connection.disconnect();
191 * Creates a file entry suitable for handing in to
192 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
195 * The name and hash of the file to insert
196 * @return A file entry for the given file
198 private Optional<FileEntry> createFileEntry(ScannedFile file) {
199 String filename = file.getFilename();
200 FileOption fileOption = project.getFileOption(filename);
201 if (fileOption.isInsert()) {
202 fileOption.setCurrentHash(file.getHash());
203 /* check if file was modified. */
204 if (!project.isAlwaysForceInsert() && !fileOption.isForceInsert() && file.getHash().equals(fileOption.getLastInsertHash())) {
205 /* only insert a redirect. */
206 logger.log(Level.FINE, String.format("Inserting redirect to edition %d for %s.", fileOption.getLastInsertEdition(), filename));
207 return Optional.of(new RedirectFileEntry(fileOption.getChangedName().orElse(filename), fileOption.getMimeType(), "SSK@" + project.getRequestURI() + "/" + project.getPath() + "-" + fileOption.getLastInsertEdition() + "/" + fileOption.getLastInsertFilename()));
210 return Optional.of(createFileEntry(filename, fileOption.getChangedName(), fileOption.getMimeType()));
211 } catch (IOException ioe1) {
212 /* ignore, null is returned. */
215 if (fileOption.isInsertRedirect()) {
216 return Optional.of(new RedirectFileEntry(fileOption.getChangedName().orElse(filename), fileOption.getMimeType(), fileOption.getCustomKey()));
219 return Optional.empty();
222 private FileEntry createFileEntry(String filename, Optional<String> changedName, String mimeType) throws FileNotFoundException {
223 File physicalFile = new File(project.getLocalPath(), filename);
224 InputStream fileEntryInputStream = new FileInputStream(physicalFile);
225 return new DirectFileEntry(changedName.orElse(filename), mimeType, fileEntryInputStream, physicalFile.length());
229 * Validates the given project. The project will be checked for any invalid
230 * conditions, such as invalid insert or request keys, missing path names,
231 * missing default file, and so on.
234 * The project to check
235 * @return The encountered warnings and errors
237 public static CheckReport validateProject(Project project) {
238 CheckReport checkReport = new CheckReport();
239 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
240 checkReport.addIssue("error.no-local-path", true);
242 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
243 checkReport.addIssue("error.no-path", true);
245 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
246 checkReport.addIssue("warning.empty-index", false);
248 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
249 if (!indexFile.exists()) {
250 checkReport.addIssue("error.index-missing", true);
253 String indexFile = project.getIndexFile();
254 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
255 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
256 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
257 checkReport.addIssue("warning.index-not-html", false);
259 Map<String, FileOption> fileOptions = project.getFileOptions();
260 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
261 boolean insert = fileOptionEntries.isEmpty();
262 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
263 String fileName = fileOptionEntry.getKey();
264 FileOption fileOption = fileOptionEntry.getValue();
265 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
266 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
267 checkReport.addIssue("error.index-not-inserted", true);
269 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
270 checkReport.addIssue("error.no-custom-key", true, fileName);
274 checkReport.addIssue("error.no-files-to-insert", true);
276 Set<String> fileNames = new HashSet<String>();
277 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
278 FileOption fileOption = fileOptionEntry.getValue();
279 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
280 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
283 String fileName = fileOption.getChangedName().orElse(fileOptionEntry.getKey());
284 logger.log(Level.FINEST, "Adding ā{0}ā for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
285 if (!fileNames.add(fileName)) {
286 checkReport.addIssue("error.duplicate-file", true, fileName);
290 final CountDownLatch completionLatch = new CountDownLatch(1);
291 FileScanner fileScanner = new FileScanner(project, new FileScannerListener() {
294 public void fileScannerFinished(FileScanner fileScanner) {
295 completionLatch.countDown();
298 fileScanner.startInBackground();
299 while (completionLatch.getCount() > 0) {
301 completionLatch.await();
302 } catch (InterruptedException ie1) {
306 for (ScannedFile scannedFile : fileScanner.getFiles()) {
307 String fileName = scannedFile.getFilename();
308 FileOption fileOption = project.getFileOption(fileName);
309 if ((fileOption != null) && !fileOption.isInsert()) {
312 totalSize += new File(project.getLocalPath(), fileName).length();
314 if (totalSize > 2 * 1024 * 1024) {
315 checkReport.addIssue("warning.site-larger-than-2-mib", false);
325 projectInsertListeners.fireProjectInsertStarted(project);
326 List<ScannedFile> files = fileScanner.getFiles();
328 /* create connection to node */
329 synchronized (lockObject) {
330 connection = freenetInterface.getConnection("project-insert-" + random + counter.getAndIncrement());
332 connection.setTempDirectory(tempDirectory);
333 boolean connected = false;
334 Throwable cause = null;
336 connected = connection.connect();
337 } catch (IOException e1) {
341 if (!connected || cancelled) {
342 projectInsertListeners.fireProjectInsertFinished(project, false, cancelled ? new AbortedException() : cause);
346 Client client = new Client(connection);
349 int edition = project.getEdition();
350 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
351 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter.getAndIncrement(), dirURI, tempDirectory);
352 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
353 FileOption indexFileOption = project.getFileOption(project.getIndexFile());
354 Optional<String> changedName = indexFileOption.getChangedName();
355 if (changedName.isPresent()) {
356 putDir.setDefaultName(changedName.get());
358 putDir.setDefaultName(project.getIndexFile());
361 putDir.setVerbosity(Verbosity.ALL);
362 putDir.setMaxRetries(-1);
363 putDir.setEarlyEncode(useEarlyEncode);
364 putDir.setPriorityClass(priority);
365 for (ScannedFile file : files) {
366 Optional<FileEntry> fileEntry = createFileEntry(file);
367 if (fileEntry.isPresent()) {
369 putDir.addFileEntry(fileEntry.get());
370 } catch (IOException ioe1) {
371 projectInsertListeners.fireProjectInsertFinished(project, false, ioe1);
379 client.execute(putDir, progressListener);
380 projectInsertListeners.fireProjectUploadFinished(project);
381 } catch (IOException ioe1) {
382 projectInsertListeners.fireProjectInsertFinished(project, false, ioe1);
386 /* parse progress and success messages */
387 String finalURI = null;
388 boolean success = false;
389 boolean finished = false;
390 boolean disconnected = false;
391 while (!finished && !cancelled) {
392 Message message = client.readMessage();
393 finished = (message == null) || (disconnected = client.isDisconnected());
394 logger.log(Level.FINE, "Received message: " + message);
396 @SuppressWarnings("null")
397 String messageName = message.getName();
398 if ("URIGenerated".equals(messageName)) {
399 finalURI = message.get("URI");
400 projectInsertListeners.fireProjectURIGenerated(project, finalURI);
402 if ("SimpleProgress".equals(messageName)) {
403 int total = Integer.parseInt(message.get("Total"));
404 int succeeded = Integer.parseInt(message.get("Succeeded"));
405 int fatal = Integer.parseInt(message.get("FatallyFailed"));
406 int failed = Integer.parseInt(message.get("Failed"));
407 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
408 projectInsertListeners.fireProjectInsertProgress(project, succeeded, failed, fatal, total, finalized);
410 success |= "PutSuccessful".equals(messageName);
411 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
415 /* post-insert work */
417 @SuppressWarnings("null")
418 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
419 int newEdition = Integer.parseInt(editionPart);
420 project.setEdition(newEdition);
421 project.setLastInsertionTime(System.currentTimeMillis());
422 project.onSuccessfulInsert();
424 projectInsertListeners.fireProjectInsertFinished(project, success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
428 // INTERFACE FileScannerListener
435 public void fileScannerFinished(FileScanner fileScanner) {
436 if (!fileScanner.isError()) {
437 new Thread(this).start();
439 projectInsertListeners.fireProjectInsertFinished(project, false, null);
444 * Container class that collects all warnings and errors that occured during
445 * {@link ProjectInserter#validateProject(Project) project validation}.
447 * @author <a href="mailto:bombe@pterodactylus.net">David āBombeā Roden</a>
449 public static class CheckReport implements Iterable<Issue> {
451 /** The issures that occured. */
452 private final List<Issue> issues = new ArrayList<Issue>();
460 public void addIssue(Issue issue) {
465 * Creates an {@link Issue} from the given error key and fatality flag
466 * and {@link #addIssue(Issue) adds} it.
471 * {@code true} if the error is fatal, {@code false} if only
472 * a warning should be generated
474 * Any additional parameters
476 public void addIssue(String errorKey, boolean fatal, String... parameters) {
477 addIssue(new Issue(errorKey, fatal, parameters));
484 public Iterator<Issue> iterator() {
485 return issues.iterator();
489 * Returns whether this check report does not contain any errors.
491 * @return {@code true} if this check report does not contain any
492 * errors, {@code false} if this check report does contain
495 public boolean isEmpty() {
496 return issues.isEmpty();
500 * Returns the number of issues in this check report.
502 * @return The number of issues
505 return issues.size();
511 * Container class for a single issue. An issue contains an error key
512 * that describes the error, and a fatality flag that determines whether
513 * the insert has to be aborted (if the flag is {@code true}) or if it
514 * can still be performed and only a warning should be generated (if the
515 * flag is {@code false}).
517 * @author <a href="mailto:bombe@pterodactylus.net">David āBombeā
520 public static class Issue {
522 /** The error key. */
523 private final String errorKey;
525 /** The fatality flag. */
526 private final boolean fatal;
528 /** Additional parameters. */
529 private String[] parameters;
532 * Creates a new issue.
539 * Any additional parameters
541 protected Issue(String errorKey, boolean fatal, String... parameters) {
542 this.errorKey = errorKey;
544 this.parameters = parameters;
548 * Returns the key of the encountered error.
550 * @return The error key
552 public String getErrorKey() {
557 * Returns whether the issue is fatal and the insert has to be
558 * aborted. Otherwise only a warning should be shown.
560 * @return {@code true} if the insert needs to be aborted, {@code
563 public boolean isFatal() {
568 * Returns any additional parameters.
570 * @return The additional parameters
572 public String[] getParameters() {