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