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