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