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.Collection;
29 import java.util.HashSet;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Optional;
36 import java.util.concurrent.CountDownLatch;
37 import java.util.concurrent.atomic.AtomicInteger;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
41 import net.pterodactylus.util.io.StreamCopier.ProgressListener;
43 import de.todesbaum.jsite.gui.FileScanner;
44 import de.todesbaum.jsite.gui.ScannedFile;
45 import de.todesbaum.jsite.gui.FileScannerListener;
46 import de.todesbaum.util.freenet.fcp2.Client;
47 import de.todesbaum.util.freenet.fcp2.ClientPutComplexDir;
48 import de.todesbaum.util.freenet.fcp2.Connection;
49 import de.todesbaum.util.freenet.fcp2.DirectFileEntry;
50 import de.todesbaum.util.freenet.fcp2.FileEntry;
51 import de.todesbaum.util.freenet.fcp2.Message;
52 import de.todesbaum.util.freenet.fcp2.PriorityClass;
53 import de.todesbaum.util.freenet.fcp2.RedirectFileEntry;
54 import de.todesbaum.util.freenet.fcp2.Verbosity;
57 * Manages project inserts.
59 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
61 public class ProjectInserter implements FileScannerListener, Runnable {
64 private static final Logger logger = Logger.getLogger(ProjectInserter.class.getName());
66 /** Random number for FCP instances. */
67 private static final int random = (int) (Math.random() * Integer.MAX_VALUE);
69 /** Counter for FCP connection identifier. */
70 private static final AtomicInteger counter = new AtomicInteger();
72 private final ProjectInsertListeners projectInsertListeners = new ProjectInsertListeners();
74 /** The freenet interface. */
75 private Freenet7Interface freenetInterface;
77 /** The project to insert. */
78 private Project project;
80 /** The file scanner. */
81 private FileScanner fileScanner;
83 /** Object used for synchronization. */
84 private final Object lockObject = new Object();
86 /** The temp directory. */
87 private String tempDirectory;
89 /** The current connection. */
90 private Connection connection;
92 /** Whether the insert is cancelled. */
93 private volatile boolean cancelled = false;
95 /** Progress listener for payload transfers. */
96 private ProgressListener progressListener;
98 /** Whether to use “early encode.” */
99 private boolean useEarlyEncode;
101 /** The insert priority. */
102 private PriorityClass priority;
105 * Adds a listener to the list of registered listeners.
107 * @param insertListener
108 * The listener to add
110 public void addInsertListener(InsertListener insertListener) {
111 projectInsertListeners.addInsertListener(insertListener);
115 * Sets the project to insert.
118 * The project to insert
120 public void setProject(Project project) {
121 this.project = project;
125 * Sets the freenet interface to use.
127 * @param freenetInterface
128 * The freenet interface to use
130 public void setFreenetInterface(Freenet7Interface freenetInterface) {
131 this.freenetInterface = freenetInterface;
135 * Sets the temp directory to use.
137 * @param tempDirectory
138 * The temp directory to use, or {@code null} to use the system
141 public void setTempDirectory(String tempDirectory) {
142 this.tempDirectory = tempDirectory;
146 * Sets whether to use the “early encode“ flag for the insert.
148 * @param useEarlyEncode
149 * {@code true} to set the “early encode” flag for the insert,
150 * {@code false} otherwise
152 public void setUseEarlyEncode(boolean useEarlyEncode) {
153 this.useEarlyEncode = useEarlyEncode;
157 * Sets the insert priority.
160 * The insert priority
162 public void setPriority(PriorityClass priority) {
163 this.priority = priority;
169 * @param progressListener
170 * Listener to notify on progress events
172 public void start(ProgressListener progressListener) {
174 this.progressListener = progressListener;
175 fileScanner = new FileScanner(project, this);
176 fileScanner.startInBackground();
180 * Stops the current insert.
184 synchronized (lockObject) {
185 if (connection != null) {
186 connection.disconnect();
192 * Creates a file entry suitable for handing in to
193 * {@link ClientPutComplexDir#addFileEntry(FileEntry)}.
196 * The name and hash of the file to insert
197 * @return A file entry for the given file
199 private Optional<FileEntry> createFileEntry(ScannedFile file) {
200 String filename = file.getFilename();
201 FileOption fileOption = project.getFileOption(filename);
202 if (fileOption.isInsert()) {
203 fileOption.setCurrentHash(file.getHash());
204 /* check if file was modified. */
205 if (!project.isAlwaysForceInsert() && !fileOption.isForceInsert() && file.getHash().equals(fileOption.getLastInsertHash())) {
206 /* only insert a redirect. */
207 logger.log(Level.FINE, String.format("Inserting redirect to edition %d for %s.", fileOption.getLastInsertEdition(), filename));
208 return Optional.of(new RedirectFileEntry(fileOption.getChangedName().orElse(filename), fileOption.getMimeType(), "SSK@" + project.getRequestURI() + "/" + project.getPath() + "-" + fileOption.getLastInsertEdition() + "/" + fileOption.getLastInsertFilename()));
211 return Optional.of(createFileEntry(filename, fileOption.getChangedName(), fileOption.getMimeType()));
212 } catch (IOException ioe1) {
213 /* ignore, null is returned. */
216 if (fileOption.isInsertRedirect()) {
217 return Optional.of(new RedirectFileEntry(fileOption.getChangedName().orElse(filename), fileOption.getMimeType(), fileOption.getCustomKey()));
220 return Optional.empty();
223 private FileEntry createFileEntry(String filename, Optional<String> changedName, String mimeType) throws FileNotFoundException {
224 File physicalFile = new File(project.getLocalPath(), filename);
225 InputStream fileEntryInputStream = new FileInputStream(physicalFile);
226 return new DirectFileEntry(changedName.orElse(filename), mimeType, fileEntryInputStream, physicalFile.length());
230 * Validates the given project. The project will be checked for any invalid
231 * conditions, such as invalid insert or request keys, missing path names,
232 * missing default file, and so on.
235 * The project to check
236 * @return The encountered warnings and errors
238 public static CheckReport validateProject(Project project) {
239 CheckReport checkReport = new CheckReport();
240 if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
241 checkReport.addIssue("error.no-local-path", true);
243 if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
244 checkReport.addIssue("error.no-path", true);
246 if ((project.getIndexFile() == null) || (project.getIndexFile().length() == 0)) {
247 checkReport.addIssue("warning.empty-index", false);
249 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
250 if (!indexFile.exists()) {
251 checkReport.addIssue("error.index-missing", true);
254 String indexFile = project.getIndexFile();
255 boolean hasIndexFile = (indexFile != null) && (indexFile.length() > 0);
256 List<String> allowedIndexContentTypes = Arrays.asList("text/html", "application/xhtml+xml");
257 if (hasIndexFile && !allowedIndexContentTypes.contains(project.getFileOption(indexFile).getMimeType())) {
258 checkReport.addIssue("warning.index-not-html", false);
260 Map<String, FileOption> fileOptions = project.getFileOptions();
261 Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
262 boolean insert = fileOptionEntries.isEmpty();
263 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
264 String fileName = fileOptionEntry.getKey();
265 FileOption fileOption = fileOptionEntry.getValue();
266 insert |= fileOption.isInsert() || fileOption.isInsertRedirect();
267 if (fileName.equals(project.getIndexFile()) && !fileOption.isInsert() && !fileOption.isInsertRedirect()) {
268 checkReport.addIssue("error.index-not-inserted", true);
270 if (!fileOption.isInsert() && fileOption.isInsertRedirect() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
271 checkReport.addIssue("error.no-custom-key", true, fileName);
275 checkReport.addIssue("error.no-files-to-insert", true);
277 Set<String> fileNames = new HashSet<String>();
278 for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
279 FileOption fileOption = fileOptionEntry.getValue();
280 if (!fileOption.isInsert() && !fileOption.isInsertRedirect()) {
281 logger.log(Level.FINEST, "Ignoring {0}.", fileOptionEntry.getKey());
284 String fileName = fileOption.getChangedName().orElse(fileOptionEntry.getKey());
285 logger.log(Level.FINEST, "Adding “{0}” for {1}.", new Object[] { fileName, fileOptionEntry.getKey() });
286 if (!fileNames.add(fileName)) {
287 checkReport.addIssue("error.duplicate-file", true, fileName);
291 final CountDownLatch completionLatch = new CountDownLatch(1);
292 FileScanner fileScanner = new FileScanner(project, (error, files) -> completionLatch.countDown());
293 fileScanner.startInBackground();
294 while (completionLatch.getCount() > 0) {
296 completionLatch.await();
297 } catch (InterruptedException ie1) {
301 for (ScannedFile scannedFile : fileScanner.getFiles()) {
302 String fileName = scannedFile.getFilename();
303 FileOption fileOption = project.getFileOption(fileName);
304 if ((fileOption != null) && !fileOption.isInsert()) {
307 totalSize += new File(project.getLocalPath(), fileName).length();
309 if (totalSize > 2 * 1024 * 1024) {
310 checkReport.addIssue("warning.site-larger-than-2-mib", false);
320 projectInsertListeners.fireProjectInsertStarted(project);
321 List<ScannedFile> files = fileScanner.getFiles();
323 /* create connection to node */
324 synchronized (lockObject) {
325 connection = freenetInterface.getConnection("project-insert-" + random + counter.getAndIncrement());
327 connection.setTempDirectory(tempDirectory);
328 boolean connected = false;
329 Throwable cause = null;
331 connected = connection.connect();
332 } catch (IOException e1) {
336 if (!connected || cancelled) {
337 projectInsertListeners.fireProjectInsertFinished(project, false, cancelled ? new AbortedException() : cause);
341 Client client = new Client(connection);
344 int edition = project.getEdition();
345 String dirURI = "USK@" + project.getInsertURI() + "/" + project.getPath() + "/" + edition + "/";
346 ClientPutComplexDir putDir = new ClientPutComplexDir("dir-" + counter.getAndIncrement(), dirURI, tempDirectory);
347 if ((project.getIndexFile() != null) && (project.getIndexFile().length() > 0)) {
348 FileOption indexFileOption = project.getFileOption(project.getIndexFile());
349 Optional<String> changedName = indexFileOption.getChangedName();
350 if (changedName.isPresent()) {
351 putDir.setDefaultName(changedName.get());
353 putDir.setDefaultName(project.getIndexFile());
356 putDir.setVerbosity(Verbosity.ALL);
357 putDir.setMaxRetries(-1);
358 putDir.setEarlyEncode(useEarlyEncode);
359 putDir.setPriorityClass(priority);
360 for (ScannedFile file : files) {
361 Optional<FileEntry> fileEntry = createFileEntry(file);
362 if (fileEntry.isPresent()) {
364 putDir.addFileEntry(fileEntry.get());
365 } catch (IOException ioe1) {
366 projectInsertListeners.fireProjectInsertFinished(project, false, ioe1);
374 client.execute(putDir, progressListener);
375 projectInsertListeners.fireProjectUploadFinished(project);
376 } catch (IOException ioe1) {
377 projectInsertListeners.fireProjectInsertFinished(project, false, ioe1);
381 /* parse progress and success messages */
382 String finalURI = null;
383 boolean success = false;
384 boolean finished = false;
385 boolean disconnected = false;
386 while (!finished && !cancelled) {
387 Message message = client.readMessage();
388 finished = (message == null) || (disconnected = client.isDisconnected());
389 logger.log(Level.FINE, "Received message: " + message);
391 @SuppressWarnings("null")
392 String messageName = message.getName();
393 if ("URIGenerated".equals(messageName)) {
394 finalURI = message.get("URI");
395 projectInsertListeners.fireProjectURIGenerated(project, finalURI);
397 if ("SimpleProgress".equals(messageName)) {
398 int total = Integer.parseInt(message.get("Total"));
399 int succeeded = Integer.parseInt(message.get("Succeeded"));
400 int fatal = Integer.parseInt(message.get("FatallyFailed"));
401 int failed = Integer.parseInt(message.get("Failed"));
402 boolean finalized = Boolean.parseBoolean(message.get("FinalizedTotal"));
403 projectInsertListeners.fireProjectInsertProgress(project, succeeded, failed, fatal, total, finalized);
405 success |= "PutSuccessful".equals(messageName);
406 finished = (success && (finalURI != null)) || "PutFailed".equals(messageName) || messageName.endsWith("Error");
410 /* post-insert work */
412 @SuppressWarnings("null")
413 String editionPart = finalURI.substring(finalURI.lastIndexOf('/') + 1);
414 int newEdition = Integer.parseInt(editionPart);
415 project.setEdition(newEdition);
416 project.setLastInsertionTime(System.currentTimeMillis());
417 project.onSuccessfulInsert();
419 projectInsertListeners.fireProjectInsertFinished(project, success, cancelled ? new AbortedException() : (disconnected ? new IOException("Connection terminated") : null));
423 // INTERFACE FileScannerListener
430 public void fileScannerFinished(boolean error, Collection<ScannedFile> files) {
432 new Thread(this).start();
434 projectInsertListeners.fireProjectInsertFinished(project, false, null);
439 * Container class that collects all warnings and errors that occured during
440 * {@link ProjectInserter#validateProject(Project) project validation}.
442 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
444 public static class CheckReport implements Iterable<Issue> {
446 /** The issures that occured. */
447 private final List<Issue> issues = new ArrayList<Issue>();
455 public void addIssue(Issue issue) {
460 * Creates an {@link Issue} from the given error key and fatality flag
461 * and {@link #addIssue(Issue) adds} it.
466 * {@code true} if the error is fatal, {@code false} if only
467 * a warning should be generated
469 * Any additional parameters
471 public void addIssue(String errorKey, boolean fatal, String... parameters) {
472 addIssue(new Issue(errorKey, fatal, parameters));
479 public Iterator<Issue> iterator() {
480 return issues.iterator();
484 * Returns whether this check report does not contain any errors.
486 * @return {@code true} if this check report does not contain any
487 * errors, {@code false} if this check report does contain
490 public boolean isEmpty() {
491 return issues.isEmpty();
495 * Returns the number of issues in this check report.
497 * @return The number of issues
500 return issues.size();
506 * Container class for a single issue. An issue contains an error key
507 * that describes the error, and a fatality flag that determines whether
508 * the insert has to be aborted (if the flag is {@code true}) or if it
509 * can still be performed and only a warning should be generated (if the
510 * flag is {@code false}).
512 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
515 public static class Issue {
517 /** The error key. */
518 private final String errorKey;
520 /** The fatality flag. */
521 private final boolean fatal;
523 /** Additional parameters. */
524 private String[] parameters;
527 * Creates a new issue.
534 * Any additional parameters
536 protected Issue(String errorKey, boolean fatal, String... parameters) {
537 this.errorKey = errorKey;
539 this.parameters = parameters;
543 * Returns the key of the encountered error.
545 * @return The error key
547 public String getErrorKey() {
552 * Returns whether the issue is fatal and the insert has to be
553 * aborted. Otherwise only a warning should be shown.
555 * @return {@code true} if the insert needs to be aborted, {@code
558 public boolean isFatal() {
563 * Returns any additional parameters.
565 * @return The additional parameters
567 public String[] getParameters() {