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