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