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