bbe76c7136a33f9e5f2ff9561ee540239c378116
[jSite.git] / src / main / java / de / todesbaum / jsite / main / CLI.java
1 /*
2  * jSite - CLI.java - Copyright © 2006–2012 David Roden
3  *
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.
8  *
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.
13  *
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.
17  */
18
19 package de.todesbaum.jsite.main;
20
21 import java.io.PrintWriter;
22
23 import net.pterodactylus.util.io.StreamCopier.ProgressListener;
24 import de.todesbaum.jsite.application.Freenet7Interface;
25 import de.todesbaum.jsite.application.InsertListener;
26 import de.todesbaum.jsite.application.Node;
27 import de.todesbaum.jsite.application.Project;
28 import de.todesbaum.jsite.application.ProjectInserter;
29
30 /**
31  * Command-line interface for jSite.
32  *
33  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
34  */
35 public class CLI implements InsertListener {
36
37         /** Object used for synchronization. */
38         private Object lockObject = new Object();
39
40         /** Writer for the console. */
41         private PrintWriter outputWriter = new PrintWriter(System.out, true);
42
43         /** The freenet interface. */
44         private Freenet7Interface freenetInterface;
45
46         /** The project inserter. */
47         private ProjectInserter projectInserter = new ProjectInserter();
48
49         /** The list of nodes. */
50         private Node[] nodes;
51
52         /** The projects. */
53         private Project[] projects;
54
55         /** Whether the insert has finished. */
56         private boolean finished = false;
57
58         /** Whether the insert finished successfully. */
59         private boolean success;
60
61         /**
62          * Creates a new command-line interface.
63          *
64          * @param args
65          *            The command-line arguments
66          */
67         private CLI(String[] args) {
68
69                 if ((args.length == 0) || args[0].equals("-h") || args[0].equals("--help")) {
70                         outputWriter.println("\nParameters:\n");
71                         outputWriter.println("  --config-file=<configuration file>");
72                         outputWriter.println("  --node=<node name>");
73                         outputWriter.println("  --project=<project name>");
74                         outputWriter.println("  --local-directory=<local directory>");
75                         outputWriter.println("  --path=<path>");
76                         outputWriter.println("  --edition=<edition>");
77                         outputWriter.println("\nA project gets inserted when a new project is loaded on the command line,");
78                         outputWriter.println("or when the command line is finished. --local-directory, --path, and --edition");
79                         outputWriter.println("override the parameters in the project.");
80                         return;
81                 }
82
83                 String configFile = System.getProperty("user.home") + "/.jSite/config7";
84                 for (String argument : args) {
85                         String value = argument.substring(argument.indexOf('=') + 1).trim();
86                         if (argument.startsWith("--config-file=")) {
87                                 configFile = value;
88                         }
89                 }
90
91                 ConfigurationLocator configurationLocator = new ConfigurationLocator();
92                 if (configFile != null) {
93                         configurationLocator.setCustomLocation(configFile);
94                 }
95                 Configuration configuration = new Configuration(configurationLocator, configurationLocator.findPreferredLocation());
96
97                 projectInserter.addInsertListener(this);
98                 projects = configuration.getProjects();
99                 Node node = configuration.getSelectedNode();
100                 nodes = configuration.getNodes();
101
102                 freenetInterface = new Freenet7Interface();
103                 freenetInterface.setNode(node);
104
105                 projectInserter.setFreenetInterface(freenetInterface);
106
107                 Project currentProject = null;
108                 for (String argument : args) {
109                         if (argument.startsWith("--config-file=")) {
110                                 /* we already parsed this one. */
111                                 continue;
112                         }
113                         String value = argument.substring(argument.indexOf('=') + 1).trim();
114                         if (argument.startsWith("--node=")) {
115                                 Node newNode = getNode(value);
116                                 if (newNode == null) {
117                                         outputWriter.println("Node \"" + value + "\" not found.");
118                                         return;
119                                 }
120                                 node = newNode;
121                                 freenetInterface.setNode(node);
122                         } else if (argument.startsWith("--project=")) {
123                                 if (currentProject != null) {
124                                         if (insertProject(currentProject)) {
125                                                 outputWriter.println("Project \"" + currentProject.getName() + "\" successfully inserted.");
126                                         } else {
127                                                 outputWriter.println("Project \"" + currentProject.getName() + "\" was not successfully inserted.");
128                                         }
129                                         currentProject = null;
130                                 }
131                                 currentProject = getProject(value);
132                                 if (currentProject == null) {
133                                         outputWriter.println("Project \"" + value + "\" not found.");
134                                 }
135                         } else if (argument.startsWith("--local-directory")) {
136                                 if (currentProject == null) {
137                                         outputWriter.println("You can't specifiy --local-directory before --project.");
138                                         return;
139                                 }
140                                 currentProject.setLocalPath(value);
141                         } else if (argument.startsWith("--path=")) {
142                                 if (currentProject == null) {
143                                         outputWriter.println("You can't specify --path before --project.");
144                                         return;
145                                 }
146                                 currentProject.setPath(value);
147                         } else if (argument.startsWith("--edition=")) {
148                                 if (currentProject == null) {
149                                         outputWriter.println("You can't specify --edition before --project.");
150                                         return;
151                                 }
152                                 currentProject.setEdition(Integer.parseInt(value));
153                         } else {
154                                 outputWriter.println("Unknown parameter: " + argument);
155                                 return;
156                         }
157                 }
158
159                 int errorCode = 1;
160                 if (currentProject != null) {
161                         if (insertProject(currentProject)) {
162                                 outputWriter.println("Project \"" + currentProject.getName() + "\" successfully inserted.");
163                                 errorCode = 0;
164                         } else {
165                                 outputWriter.println("Project \"" + currentProject.getName() + "\" was not successfully inserted.");
166                         }
167                 }
168
169                 configuration.setProjects(projects);
170                 configuration.save();
171
172                 System.exit(errorCode);
173         }
174
175         /**
176          * Returns the project with the given name.
177          *
178          * @param name
179          *            The name of the project
180          * @return The project, or <code>null</code> if no project could be found
181          */
182         private Project getProject(String name) {
183                 for (Project project : projects) {
184                         if (project.getName().equals(name)) {
185                                 return project;
186                         }
187                 }
188                 return null;
189         }
190
191         /**
192          * Returns the node with the given name.
193          *
194          * @param name
195          *            The name of the node
196          * @return The node, or <code>null</code> if no node could be found
197          */
198         private Node getNode(String name) {
199                 for (Node node : nodes) {
200                         if (node.getName().equals(name)) {
201                                 return node;
202                         }
203                 }
204                 return null;
205         }
206
207         /**
208          * Inserts the given project.
209          *
210          * @param currentProject
211          *            The project to insert
212          * @return <code>true</code> if the insert finished successfully,
213          *         <code>false</code> otherwise
214          */
215         private boolean insertProject(Project currentProject) {
216                 if (!freenetInterface.hasNode()) {
217                         outputWriter.println("Node is not running!");
218                         return false;
219                 }
220                 projectInserter.setProject(currentProject);
221                 projectInserter.start(new ProgressListener() {
222
223                         @Override
224                         public void onProgress(long copied, long length) {
225                                 System.out.print("Uploaded: " + copied + " / " + length + " bytes...\r");
226                         }
227                 });
228                 synchronized (lockObject) {
229                         while (!finished) {
230                                 try {
231                                         lockObject.wait();
232                                 } catch (InterruptedException e) {
233                                         /* ignore, we're in a loop. */
234                                 }
235                         }
236                 }
237                 return success;
238         }
239
240         //
241         // INTERFACE InsertListener
242         //
243
244         /**
245          * {@inheritDoc}
246          */
247         @Override
248         public void projectInsertStarted(Project project) {
249                 outputWriter.println("Starting Insert of project \"" + project.getName() + "\".");
250         }
251
252         /**
253          * {@inheritDoc}
254          */
255         @Override
256         public void projectUploadFinished(Project project) {
257                 outputWriter.println("Project \"" + project.getName() + "\" has been uploaded, starting insert...");
258         }
259
260         /**
261          * {@inheritDoc}
262          */
263         @Override
264         public void projectURIGenerated(Project project, String uri) {
265                 outputWriter.println("URI: " + uri);
266         }
267
268         /**
269          * {@inheritDoc}
270          */
271         @Override
272         public void projectInsertProgress(Project project, int succeeded, int failed, int fatal, int total, boolean finalized) {
273                 outputWriter.println("Progress: " + succeeded + " done, " + failed + " failed, " + fatal + " fatal, " + total + " total" + (finalized ? " (finalized)" : "") + ", " + ((succeeded + failed + fatal) * 100 / total) + "%");
274         }
275
276         /**
277          * {@inheritDoc}
278          */
279         @Override
280         public void projectInsertFinished(Project project, boolean success, Throwable cause) {
281                 outputWriter.println("Request URI: " + project.getFinalRequestURI(0));
282                 finished = true;
283                 this.success = success;
284                 synchronized (lockObject) {
285                         lockObject.notify();
286                 }
287         }
288
289         //
290         // MAIN
291         //
292
293         /**
294          * Creates a new command-line interface with the given arguments.
295          *
296          * @param args
297          *            The command-line arguments
298          */
299         public static void main(String[] args) {
300                 new CLI(args);
301         }
302
303 }