Add custom exception for adding duplicate fields
[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.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                 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(0, 8, 9);
120
121         /** The logger. */
122         private static final Logger logger = getLogger("Sone.Plugin");
123
124         /** The plugin respirator. */
125         private PluginRespirator pluginRespirator;
126
127         /** The core. */
128         private Core core;
129
130         /** The web interface. */
131         private WebInterface webInterface;
132
133         /** The FCP interface. */
134         private FcpInterface fcpInterface;
135
136         /** The l10n helper. */
137         private PluginL10n l10n;
138
139         /** The web of trust connector. */
140         private WebOfTrustConnector webOfTrustConnector;
141
142         //
143         // ACCESSORS
144         //
145
146         /**
147          * Returns the plugin respirator for this plugin.
148          *
149          * @return The plugin respirator
150          */
151         public PluginRespirator pluginRespirator() {
152                 return pluginRespirator;
153         }
154
155         /**
156          * Returns the core started by this plugin.
157          *
158          * @return The core
159          */
160         public Core core() {
161                 return core;
162         }
163
164         /**
165          * Returns the plugin’s l10n helper.
166          *
167          * @return The plugin’s l10n helper
168          */
169         public PluginL10n l10n() {
170                 return l10n;
171         }
172
173         //
174         // FREDPLUGIN METHODS
175         //
176
177         /**
178          * {@inheritDoc}
179          */
180         @Override
181         public void runPlugin(PluginRespirator pluginRespirator) {
182                 this.pluginRespirator = pluginRespirator;
183
184                 /* create a configuration. */
185                 Configuration oldConfiguration;
186                 Configuration newConfiguration = null;
187                 boolean firstStart = !new File("sone.properties").exists();
188                 boolean newConfig = false;
189                 try {
190                         oldConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), false));
191                         newConfiguration = oldConfiguration;
192                 } catch (ConfigurationException ce1) {
193                         newConfig = true;
194                         logger.log(Level.INFO, "Could not load configuration file, trying plugin store…", ce1);
195                         try {
196                                 newConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), true));
197                                 logger.log(Level.INFO, "Created new configuration file.");
198                         } catch (ConfigurationException ce2) {
199                                 logger.log(Level.SEVERE, "Could not create configuration file, using Plugin Store!", ce2);
200                         }
201                         try {
202                                 oldConfiguration = new Configuration(new PluginStoreConfigurationBackend(pluginRespirator));
203                                 logger.log(Level.INFO, "Plugin store loaded.");
204                         } catch (DatabaseDisabledException dde1) {
205                                 logger.log(Level.SEVERE, "Could not load any configuration, using empty configuration!");
206                                 oldConfiguration = new Configuration(new MapConfigurationBackend());
207                         }
208                 }
209
210                 final Configuration startConfiguration;
211                 if ((newConfiguration != null) && (oldConfiguration != newConfiguration)) {
212                         logger.log(Level.INFO, "Setting configuration to file-based configuration.");
213                         startConfiguration = newConfiguration;
214                 } else {
215                         startConfiguration = oldConfiguration;
216                 }
217                 final EventBus eventBus = new EventBus();
218
219                 /* Freenet injector configuration. */
220                 AbstractModule freenetModule = new AbstractModule() {
221
222                         @Override
223                         @SuppressWarnings("synthetic-access")
224                         protected void configure() {
225                                 bind(PluginRespirator.class).toInstance(SonePlugin.this.pluginRespirator);
226                                 bind(Node.class).toInstance(SonePlugin.this.pluginRespirator.getNode());
227                         }
228                 };
229                 /* Sone injector configuration. */
230                 AbstractModule soneModule = new AbstractModule() {
231
232                         @Override
233                         protected void configure() {
234                                 bind(EventBus.class).toInstance(eventBus);
235                                 bind(Configuration.class).toInstance(startConfiguration);
236                                 Context context = new Context("Sone");
237                                 bind(Context.class).toInstance(context);
238                                 bind(getOptionalContextTypeLiteral()).toInstance(of(context));
239                                 bind(SonePlugin.class).toInstance(SonePlugin.this);
240                                 bindListener(Matchers.any(), new TypeListener() {
241
242                                         @Override
243                                         public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
244                                                 typeEncounter.register(new InjectionListener<I>() {
245
246                                                         @Override
247                                                         public void afterInjection(I injectee) {
248                                                                 eventBus.register(injectee);
249                                                         }
250                                                 });
251                                         }
252                                 });
253                         }
254
255                         private TypeLiteral<Optional<Context>> getOptionalContextTypeLiteral() {
256                                 return new TypeLiteral<Optional<Context>>() {
257                                 };
258                         }
259
260                 };
261                 Injector injector = Guice.createInjector(freenetModule, soneModule);
262                 core = injector.getInstance(Core.class);
263
264                 /* create web of trust connector. */
265                 webOfTrustConnector = injector.getInstance(WebOfTrustConnector.class);
266
267                 /* create FCP interface. */
268                 fcpInterface = injector.getInstance(FcpInterface.class);
269
270                 /* create the web interface. */
271                 webInterface = injector.getInstance(WebInterface.class);
272
273                 /* start core! */
274                 core.start();
275                 webInterface.start();
276                 webInterface.setFirstStart(firstStart);
277                 webInterface.setNewConfig(newConfig);
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                 }
297         }
298
299         //
300         // INTERFACE FredPluginFCP
301         //
302
303         /**
304          * {@inheritDoc}
305          */
306         @Override
307         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
308                 fcpInterface.handle(pluginReplySender, parameters, data, accessType);
309         }
310
311         //
312         // INTERFACE FredPluginL10n
313         //
314
315         /**
316          * {@inheritDoc}
317          */
318         @Override
319         public String getString(String key) {
320                 return l10n.getBase().getString(key);
321         }
322
323         /**
324          * {@inheritDoc}
325          */
326         @Override
327         public void setLanguage(LANGUAGE newLanguage) {
328                 l10n = new PluginL10n(this, newLanguage);
329         }
330
331         //
332         // INTERFACE FredPluginBaseL10n
333         //
334
335         /**
336          * {@inheritDoc}
337          */
338         @Override
339         public String getL10nFilesBasePath() {
340                 return "i18n";
341         }
342
343         /**
344          * {@inheritDoc}
345          */
346         @Override
347         public String getL10nFilesMask() {
348                 return "sone.${lang}.properties";
349         }
350
351         /**
352          * {@inheritDoc}
353          */
354         @Override
355         public String getL10nOverrideFilesMask() {
356                 return "sone.${lang}.override.properties";
357         }
358
359         /**
360          * {@inheritDoc}
361          */
362         @Override
363         public ClassLoader getPluginClassLoader() {
364                 return SonePlugin.class.getClassLoader();
365         }
366
367         //
368         // INTERFACE FredPluginVersioned
369         //
370
371         /**
372          * {@inheritDoc}
373          */
374         @Override
375         public String getVersion() {
376                 return VERSION.toString();
377         }
378
379 }