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