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