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