Add freenet module for Guice
[Sone.git] / src / main / java / net / pterodactylus / sone / main / SonePlugin.java
1 /*
2  * Sone - SonePlugin.java - Copyright © 2010–2016 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 import static java.util.logging.Logger.getLogger;
22
23 import java.io.File;
24 import java.util.logging.Handler;
25 import java.util.logging.Level;
26 import java.util.logging.LogRecord;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.core.Core;
30 import net.pterodactylus.sone.fcp.FcpInterface;
31 import net.pterodactylus.sone.freenet.PluginStoreConfigurationBackend;
32 import net.pterodactylus.sone.freenet.wot.Context;
33 import net.pterodactylus.sone.freenet.wot.WebOfTrustConnector;
34 import net.pterodactylus.sone.web.WebInterface;
35 import net.pterodactylus.util.config.Configuration;
36 import net.pterodactylus.util.config.ConfigurationException;
37 import net.pterodactylus.util.config.MapConfigurationBackend;
38 import net.pterodactylus.util.version.Version;
39
40 import com.google.common.base.Optional;
41 import com.google.common.cache.CacheBuilder;
42 import com.google.common.cache.CacheLoader;
43 import com.google.common.cache.LoadingCache;
44 import com.google.common.eventbus.EventBus;
45 import com.google.inject.AbstractModule;
46 import com.google.inject.Guice;
47 import com.google.inject.Injector;
48 import com.google.inject.TypeLiteral;
49 import com.google.inject.matcher.Matchers;
50 import com.google.inject.spi.InjectionListener;
51 import com.google.inject.spi.TypeEncounter;
52 import com.google.inject.spi.TypeListener;
53
54 import freenet.client.async.PersistenceDisabledException;
55 import freenet.l10n.BaseL10n.LANGUAGE;
56 import freenet.l10n.PluginL10n;
57 import freenet.pluginmanager.FredPlugin;
58 import freenet.pluginmanager.FredPluginBaseL10n;
59 import freenet.pluginmanager.FredPluginFCP;
60 import freenet.pluginmanager.FredPluginL10n;
61 import freenet.pluginmanager.FredPluginThreadless;
62 import freenet.pluginmanager.FredPluginVersioned;
63 import freenet.pluginmanager.PluginReplySender;
64 import freenet.pluginmanager.PluginRespirator;
65 import freenet.support.SimpleFieldSet;
66 import freenet.support.api.Bucket;
67
68 /**
69  * This class interfaces with Freenet. It is the class that is loaded by the
70  * node and starts up the whole Sone system.
71  *
72  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
73  */
74 public class SonePlugin implements FredPlugin, FredPluginFCP, FredPluginL10n, FredPluginBaseL10n, FredPluginThreadless, FredPluginVersioned {
75
76         private static final Logger soneLogger = getLogger("net.pterodactylus.sone");
77
78         static {
79                 /* initialize logging. */
80                 soneLogger.setUseParentHandlers(false);
81                 soneLogger.addHandler(new Handler() {
82                         private final LoadingCache<String, Class<?>> classCache = CacheBuilder.newBuilder()
83                                         .build(new CacheLoader<String, Class<?>>() {
84                                                 @Override
85                                                 public Class<?> load(String key) throws Exception {
86                                                         return Class.forName(key);
87                                                 }
88                                         });
89
90                         @Override
91                         public void publish(LogRecord logRecord) {
92                                 int recordLevel = logRecord.getLevel().intValue();
93                                 Class<?> loggingClass = classCache.getUnchecked(logRecord.getLoggerName());
94                                 if (recordLevel < Level.FINE.intValue()) {
95                                         freenet.support.Logger.debug(loggingClass, logRecord.getMessage(), logRecord.getThrown());
96                                 } else if (recordLevel < Level.INFO.intValue()) {
97                                         freenet.support.Logger.minor(loggingClass, logRecord.getMessage(), logRecord.getThrown());
98                                 } else if (recordLevel < Level.WARNING.intValue()) {
99                                         freenet.support.Logger.normal(loggingClass, logRecord.getMessage(), logRecord.getThrown());
100                                 } else if (recordLevel < Level.SEVERE.intValue()) {
101                                         freenet.support.Logger.warning(loggingClass, logRecord.getMessage(), logRecord.getThrown());
102                                 } else {
103                                         freenet.support.Logger.error(loggingClass, logRecord.getMessage(), logRecord.getThrown());
104                                 }
105                         }
106
107                         @Override
108                         public void flush() {
109                         }
110
111                         @Override
112                         public void close() {
113                         }
114                 });
115         }
116
117         /** The version. */
118         private static final Version VERSION = new Version(0, 9, 6);
119
120         /** The current year at time of release. */
121         private static final int YEAR = 2016;
122         private static final String SONE_HOMEPAGE = "USK@nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI,DuQSUZiI~agF8c-6tjsFFGuZ8eICrzWCILB60nT8KKo,AQACAAE/sone/";
123         private static final int LATEST_EDITION = 73;
124
125         /** The logger. */
126         private static final Logger logger = getLogger(SonePlugin.class.getName());
127
128         /** The plugin respirator. */
129         private PluginRespirator pluginRespirator;
130
131         /** The core. */
132         private Core core;
133
134         /** The web interface. */
135         private WebInterface webInterface;
136
137         /** The FCP interface. */
138         private FcpInterface fcpInterface;
139
140         /** The l10n helper. */
141         private PluginL10n l10n;
142
143         /** The web of trust connector. */
144         private WebOfTrustConnector webOfTrustConnector;
145
146         //
147         // ACCESSORS
148         //
149
150         /**
151          * Returns the plugin respirator for this plugin.
152          *
153          * @return The plugin respirator
154          */
155         public PluginRespirator pluginRespirator() {
156                 return pluginRespirator;
157         }
158
159         /**
160          * Returns the core started by this plugin.
161          *
162          * @return The core
163          */
164         public Core core() {
165                 return core;
166         }
167
168         /**
169          * Returns the plugin’s l10n helper.
170          *
171          * @return The plugin’s l10n helper
172          */
173         public PluginL10n l10n() {
174                 return l10n;
175         }
176
177         public static String getPluginVersion() {
178                 return VERSION.toString();
179         }
180
181         public static int getYear() {
182                 return YEAR;
183         }
184
185         public static String getHomepage() {
186                 return SONE_HOMEPAGE + LATEST_EDITION;
187         }
188
189         public static long getLatestEdition() {
190                 return LATEST_EDITION;
191         }
192
193         //
194         // FREDPLUGIN METHODS
195         //
196
197         /**
198          * {@inheritDoc}
199          */
200         @Override
201         public void runPlugin(PluginRespirator pluginRespirator) {
202                 this.pluginRespirator = pluginRespirator;
203
204                 /* create a configuration. */
205                 Configuration oldConfiguration;
206                 Configuration newConfiguration = null;
207                 boolean firstStart = !new File("sone.properties").exists();
208                 boolean newConfig = false;
209                 try {
210                         oldConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), false));
211                         newConfiguration = oldConfiguration;
212                 } catch (ConfigurationException ce1) {
213                         newConfig = true;
214                         logger.log(Level.INFO, "Could not load configuration file, trying plugin store…", ce1);
215                         try {
216                                 newConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), true));
217                                 logger.log(Level.INFO, "Created new configuration file.");
218                         } catch (ConfigurationException ce2) {
219                                 logger.log(Level.SEVERE, "Could not create configuration file, using Plugin Store!", ce2);
220                         }
221                         try {
222                                 oldConfiguration = new Configuration(new PluginStoreConfigurationBackend(pluginRespirator));
223                                 logger.log(Level.INFO, "Plugin store loaded.");
224                         } catch (PersistenceDisabledException pde1) {
225                                 logger.log(Level.SEVERE, "Could not load any configuration, using empty configuration!");
226                                 oldConfiguration = new Configuration(new MapConfigurationBackend());
227                         }
228                 }
229
230                 final Configuration startConfiguration;
231                 if ((newConfiguration != null) && (oldConfiguration != newConfiguration)) {
232                         logger.log(Level.INFO, "Setting configuration to file-based configuration.");
233                         startConfiguration = newConfiguration;
234                 } else {
235                         startConfiguration = oldConfiguration;
236                 }
237                 final EventBus eventBus = new EventBus();
238
239                 /* Freenet injector configuration. */
240                 FreenetModule freenetModule =  new FreenetModule(pluginRespirator);
241
242                 /* Sone injector configuration. */
243                 AbstractModule soneModule = new AbstractModule() {
244
245                         @Override
246                         protected void configure() {
247                                 bind(EventBus.class).toInstance(eventBus);
248                                 bind(Configuration.class).toInstance(startConfiguration);
249                                 Context context = new Context("Sone");
250                                 bind(Context.class).toInstance(context);
251                                 bind(getOptionalContextTypeLiteral()).toInstance(of(context));
252                                 bind(SonePlugin.class).toInstance(SonePlugin.this);
253                                 bind(Version.class).toInstance(VERSION);
254                                 bind(PluginVersion.class).toInstance(new PluginVersion(getVersion()));
255                                 bind(PluginYear.class).toInstance(new PluginYear(getYear()));
256                                 bind(PluginHomepage.class).toInstance(new PluginHomepage(getHomepage()));
257                                 if (startConfiguration.getBooleanValue("Developer.LoadFromFilesystem").getValue(false)) {
258                                         String path = startConfiguration.getStringValue("Developer.FilesystemPath").getValue(null);
259                                         if (path != null) {
260                                                 bind(Loaders.class).toInstance(new DebugLoaders(path));
261                                         }
262                                 }
263                                 bindListener(Matchers.any(), new TypeListener() {
264
265                                         @Override
266                                         public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
267                                                 typeEncounter.register(new InjectionListener<I>() {
268
269                                                         @Override
270                                                         public void afterInjection(I injectee) {
271                                                                 eventBus.register(injectee);
272                                                         }
273                                                 });
274                                         }
275                                 });
276                         }
277
278                         private TypeLiteral<Optional<Context>> getOptionalContextTypeLiteral() {
279                                 return new TypeLiteral<Optional<Context>>() {
280                                 };
281                         }
282
283                 };
284                 Injector injector = Guice.createInjector(freenetModule, soneModule);
285                 core = injector.getInstance(Core.class);
286
287                 /* create web of trust connector. */
288                 webOfTrustConnector = injector.getInstance(WebOfTrustConnector.class);
289
290                 /* create FCP interface. */
291                 fcpInterface = injector.getInstance(FcpInterface.class);
292
293                 /* create the web interface. */
294                 webInterface = injector.getInstance(WebInterface.class);
295
296                 /* start core! */
297                 core.start();
298                 webInterface.start();
299                 webInterface.setFirstStart(firstStart);
300                 webInterface.setNewConfig(newConfig);
301         }
302
303         /**
304          * {@inheritDoc}
305          */
306         @Override
307         public void terminate() {
308                 try {
309                         /* stop the web interface. */
310                         webInterface.stop();
311
312                         /* stop the core. */
313                         core.stop();
314
315                         /* stop the web of trust connector. */
316                         webOfTrustConnector.stop();
317                 } catch (Throwable t1) {
318                         logger.log(Level.SEVERE, "Error while shutting down!", t1);
319                 } finally {
320                         deregisterLoggerHandlers();
321                 }
322         }
323
324         private void deregisterLoggerHandlers() {
325                 for (Handler handler : soneLogger.getHandlers()) {
326                         soneLogger.removeHandler(handler);
327                 }
328         }
329
330         //
331         // INTERFACE FredPluginFCP
332         //
333
334         /**
335          * {@inheritDoc}
336          */
337         @Override
338         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
339                 fcpInterface.handle(pluginReplySender, parameters, data, accessType);
340         }
341
342         //
343         // INTERFACE FredPluginL10n
344         //
345
346         /**
347          * {@inheritDoc}
348          */
349         @Override
350         public String getString(String key) {
351                 return l10n.getBase().getString(key);
352         }
353
354         /**
355          * {@inheritDoc}
356          */
357         @Override
358         public void setLanguage(LANGUAGE newLanguage) {
359                 l10n = new PluginL10n(this, newLanguage);
360         }
361
362         //
363         // INTERFACE FredPluginBaseL10n
364         //
365
366         /**
367          * {@inheritDoc}
368          */
369         @Override
370         public String getL10nFilesBasePath() {
371                 return "i18n";
372         }
373
374         /**
375          * {@inheritDoc}
376          */
377         @Override
378         public String getL10nFilesMask() {
379                 return "sone.${lang}.properties";
380         }
381
382         /**
383          * {@inheritDoc}
384          */
385         @Override
386         public String getL10nOverrideFilesMask() {
387                 return "sone.${lang}.override.properties";
388         }
389
390         /**
391          * {@inheritDoc}
392          */
393         @Override
394         public ClassLoader getPluginClassLoader() {
395                 return SonePlugin.class.getClassLoader();
396         }
397
398         //
399         // INTERFACE FredPluginVersioned
400         //
401
402         /**
403          * {@inheritDoc}
404          */
405         @Override
406         public String getVersion() {
407                 return VERSION.toString();
408         }
409
410         public static class PluginVersion {
411
412                 private final String version;
413
414                 public PluginVersion(String version) {
415                         this.version = version;
416                 }
417
418                 public String getVersion() {
419                         return version;
420                 }
421
422         }
423
424         public static class PluginYear {
425
426                 private final int year;
427
428                 public PluginYear(int year) {
429                         this.year = year;
430                 }
431
432                 public int getYear() {
433                         return year;
434                 }
435
436         }
437
438         public static class PluginHomepage {
439
440                 private final String homepage;
441
442                 public PluginHomepage(String homepage) {
443                         this.homepage = homepage;
444                 }
445
446                 public String getHomepage() {
447                         return homepage;
448                 }
449
450         }
451
452 }