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