Replace utils’ SetBuilder by Guava’s ImmutableSet.Builder.
[Sone.git] / src / main / java / net / pterodactylus / sone / main / SonePlugin.java
1 /*
2  * Sone - SonePlugin.java - Copyright © 2010–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 3 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, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.main;
19
20 import java.io.File;
21 import java.util.logging.Level;
22 import java.util.logging.LogRecord;
23 import java.util.logging.Logger;
24
25 import net.pterodactylus.sone.core.Core;
26 import net.pterodactylus.sone.core.FreenetInterface;
27 import net.pterodactylus.sone.core.WebOfTrustUpdater;
28 import net.pterodactylus.sone.fcp.FcpInterface;
29 import net.pterodactylus.sone.freenet.PluginStoreConfigurationBackend;
30 import net.pterodactylus.sone.freenet.plugin.PluginConnector;
31 import net.pterodactylus.sone.freenet.wot.IdentityManager;
32 import net.pterodactylus.sone.freenet.wot.WebOfTrustConnector;
33 import net.pterodactylus.sone.web.WebInterface;
34 import net.pterodactylus.util.config.Configuration;
35 import net.pterodactylus.util.config.ConfigurationException;
36 import net.pterodactylus.util.config.MapConfigurationBackend;
37 import net.pterodactylus.util.logging.Logging;
38 import net.pterodactylus.util.logging.LoggingListener;
39 import net.pterodactylus.util.version.Version;
40
41 import com.google.inject.AbstractModule;
42 import com.google.inject.Guice;
43 import com.google.inject.Injector;
44 import com.google.inject.Singleton;
45 import com.google.inject.name.Names;
46
47 import freenet.client.async.DatabaseDisabledException;
48 import freenet.l10n.BaseL10n.LANGUAGE;
49 import freenet.l10n.PluginL10n;
50 import freenet.node.Node;
51 import freenet.pluginmanager.FredPlugin;
52 import freenet.pluginmanager.FredPluginBaseL10n;
53 import freenet.pluginmanager.FredPluginFCP;
54 import freenet.pluginmanager.FredPluginL10n;
55 import freenet.pluginmanager.FredPluginThreadless;
56 import freenet.pluginmanager.FredPluginVersioned;
57 import freenet.pluginmanager.PluginReplySender;
58 import freenet.pluginmanager.PluginRespirator;
59 import freenet.support.SimpleFieldSet;
60 import freenet.support.api.Bucket;
61
62 /**
63  * This class interfaces with Freenet. It is the class that is loaded by the
64  * node and starts up the whole Sone system.
65  *
66  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
67  */
68 public class SonePlugin implements FredPlugin, FredPluginFCP, FredPluginL10n, FredPluginBaseL10n, FredPluginThreadless, FredPluginVersioned {
69
70         static {
71                 /* initialize logging. */
72                 Logging.setup("sone");
73                 Logging.addLoggingListener(new LoggingListener() {
74
75                         @Override
76                         public void logged(LogRecord logRecord) {
77                                 Class<?> loggerClass = Logging.getLoggerClass(logRecord.getLoggerName());
78                                 int recordLevel = logRecord.getLevel().intValue();
79                                 if (recordLevel < Level.FINE.intValue()) {
80                                         freenet.support.Logger.debug(loggerClass, logRecord.getMessage(), logRecord.getThrown());
81                                 } else if (recordLevel < Level.INFO.intValue()) {
82                                         freenet.support.Logger.minor(loggerClass, logRecord.getMessage(), logRecord.getThrown());
83                                 } else if (recordLevel < Level.WARNING.intValue()) {
84                                         freenet.support.Logger.normal(loggerClass, logRecord.getMessage(), logRecord.getThrown());
85                                 } else if (recordLevel < Level.SEVERE.intValue()) {
86                                         freenet.support.Logger.warning(loggerClass, logRecord.getMessage(), logRecord.getThrown());
87                                 } else {
88                                         freenet.support.Logger.error(loggerClass, logRecord.getMessage(), logRecord.getThrown());
89                                 }
90                         }
91                 });
92         }
93
94         /** The version. */
95         public static final Version VERSION = new Version(0, 8, 4);
96
97         /** The logger. */
98         private static final Logger logger = Logging.getLogger(SonePlugin.class);
99
100         /** The plugin respirator. */
101         private PluginRespirator pluginRespirator;
102
103         /** The core. */
104         private Core core;
105
106         /** The web interface. */
107         private WebInterface webInterface;
108
109         /** The FCP interface. */
110         private FcpInterface fcpInterface;
111
112         /** The l10n helper. */
113         private PluginL10n l10n;
114
115         /** The web of trust connector. */
116         private WebOfTrustConnector webOfTrustConnector;
117
118         //
119         // ACCESSORS
120         //
121
122         /**
123          * Returns the plugin respirator for this plugin.
124          *
125          * @return The plugin respirator
126          */
127         public PluginRespirator pluginRespirator() {
128                 return pluginRespirator;
129         }
130
131         /**
132          * Returns the core started by this plugin.
133          *
134          * @return The core
135          */
136         public Core core() {
137                 return core;
138         }
139
140         /**
141          * Returns the plugin’s l10n helper.
142          *
143          * @return The plugin’s l10n helper
144          */
145         public PluginL10n l10n() {
146                 return l10n;
147         }
148
149         //
150         // FREDPLUGIN METHODS
151         //
152
153         /**
154          * {@inheritDoc}
155          */
156         @Override
157         public void runPlugin(PluginRespirator pluginRespirator) {
158                 this.pluginRespirator = pluginRespirator;
159
160                 /* create a configuration. */
161                 Configuration oldConfiguration;
162                 Configuration newConfiguration = null;
163                 boolean firstStart = !new File("sone.properties").exists();
164                 boolean newConfig = false;
165                 try {
166                         oldConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), false));
167                         newConfiguration = oldConfiguration;
168                 } catch (ConfigurationException ce1) {
169                         newConfig = true;
170                         logger.log(Level.INFO, "Could not load configuration file, trying plugin store…", ce1);
171                         try {
172                                 newConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), true));
173                                 logger.log(Level.INFO, "Created new configuration file.");
174                         } catch (ConfigurationException ce2) {
175                                 logger.log(Level.SEVERE, "Could not create configuration file, using Plugin Store!", ce2);
176                         }
177                         try {
178                                 oldConfiguration = new Configuration(new PluginStoreConfigurationBackend(pluginRespirator));
179                                 logger.log(Level.INFO, "Plugin store loaded.");
180                         } catch (DatabaseDisabledException dde1) {
181                                 logger.log(Level.SEVERE, "Could not load any configuration, using empty configuration!");
182                                 oldConfiguration = new Configuration(new MapConfigurationBackend());
183                         }
184                 }
185
186                 final Configuration startConfiguration = oldConfiguration;
187
188                 /* Freenet injector configuration. */
189                 AbstractModule freenetModule = new AbstractModule() {
190
191                         @Override
192                         @SuppressWarnings("synthetic-access")
193                         protected void configure() {
194                                 bind(PluginRespirator.class).toInstance(SonePlugin.this.pluginRespirator);
195                                 bind(Node.class).toInstance(SonePlugin.this.pluginRespirator.getNode());
196                         }
197                 };
198                 /* Sone injector configuration. */
199                 AbstractModule soneModule = new AbstractModule() {
200
201                         @Override
202                         protected void configure() {
203                                 bind(Configuration.class).toInstance(startConfiguration);
204                                 bind(FreenetInterface.class).in(Singleton.class);
205                                 bind(PluginConnector.class).in(Singleton.class);
206                                 bind(WebOfTrustConnector.class).in(Singleton.class);
207                                 bind(WebOfTrustUpdater.class).in(Singleton.class);
208                                 bind(IdentityManager.class).in(Singleton.class);
209                                 bind(String.class).annotatedWith(Names.named("WebOfTrustContext")).toInstance("Sone");
210                                 bind(SonePlugin.class).toInstance(SonePlugin.this);
211                                 bind(FcpInterface.class).in(Singleton.class);
212                         }
213                 };
214                 Injector injector = Guice.createInjector(freenetModule, soneModule);
215                 core = injector.getInstance(Core.class);
216
217                 /* create web of trust connector. */
218                 webOfTrustConnector = injector.getInstance(WebOfTrustConnector.class);
219
220                 /* create FCP interface. */
221                 fcpInterface = injector.getInstance(FcpInterface.class);
222                 core.setFcpInterface(fcpInterface);
223
224                 /* create the web interface. */
225                 webInterface = injector.getInstance(WebInterface.class);
226                 core.addCoreListener(webInterface);
227
228                 boolean startupFailed = true;
229                 try {
230
231                         /* start core! */
232                         core.start();
233                         if ((newConfiguration != null) && (oldConfiguration != newConfiguration)) {
234                                 logger.log(Level.INFO, "Setting configuration to file-based configuration.");
235                                 core.setConfiguration(newConfiguration);
236                         }
237                         webInterface.start();
238                         webInterface.setFirstStart(firstStart);
239                         webInterface.setNewConfig(newConfig);
240                         startupFailed = false;
241                 } finally {
242                         if (startupFailed) {
243                                 /*
244                                  * we let the exception bubble up but shut the logging down so
245                                  * that the logfile is not swamped by the installed logging
246                                  * handlers of the failed instances.
247                                  */
248                                 Logging.shutdown();
249                         }
250                 }
251         }
252
253         /**
254          * {@inheritDoc}
255          */
256         @Override
257         public void terminate() {
258                 try {
259                         /* stop the web interface. */
260                         webInterface.stop();
261
262                         /* stop the core. */
263                         core.stop();
264
265                         /* stop the web of trust connector. */
266                         webOfTrustConnector.stop();
267                 } catch (Throwable t1) {
268                         logger.log(Level.SEVERE, "Error while shutting down!", t1);
269                 } finally {
270                         /* shutdown logger. */
271                         Logging.shutdown();
272                 }
273         }
274
275         //
276         // INTERFACE FredPluginFCP
277         //
278
279         /**
280          * {@inheritDoc}
281          */
282         @Override
283         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
284                 fcpInterface.handle(pluginReplySender, parameters, data, accessType);
285         }
286
287         //
288         // INTERFACE FredPluginL10n
289         //
290
291         /**
292          * {@inheritDoc}
293          */
294         @Override
295         public String getString(String key) {
296                 return l10n.getBase().getString(key);
297         }
298
299         /**
300          * {@inheritDoc}
301          */
302         @Override
303         public void setLanguage(LANGUAGE newLanguage) {
304                 l10n = new PluginL10n(this, newLanguage);
305         }
306
307         //
308         // INTERFACE FredPluginBaseL10n
309         //
310
311         /**
312          * {@inheritDoc}
313          */
314         @Override
315         public String getL10nFilesBasePath() {
316                 return "i18n";
317         }
318
319         /**
320          * {@inheritDoc}
321          */
322         @Override
323         public String getL10nFilesMask() {
324                 return "sone.${lang}.properties";
325         }
326
327         /**
328          * {@inheritDoc}
329          */
330         @Override
331         public String getL10nOverrideFilesMask() {
332                 return "sone.${lang}.override.properties";
333         }
334
335         /**
336          * {@inheritDoc}
337          */
338         @Override
339         public ClassLoader getPluginClassLoader() {
340                 return SonePlugin.class.getClassLoader();
341         }
342
343         //
344         // INTERFACE FredPluginVersioned
345         //
346
347         /**
348          * {@inheritDoc}
349          */
350         @Override
351         public String getVersion() {
352                 return VERSION.toString();
353         }
354
355 }