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