Add some logging.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * FreenetSone - Core.java - Copyright © 2010 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.core;
19
20 import java.net.MalformedURLException;
21 import java.util.Collections;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Set;
25 import java.util.UUID;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.core.SoneException.Type;
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.util.config.Configuration;
32 import net.pterodactylus.util.config.ConfigurationException;
33 import net.pterodactylus.util.logging.Logging;
34 import net.pterodactylus.util.service.AbstractService;
35 import net.pterodactylus.util.text.StringEscaper;
36 import net.pterodactylus.util.text.TextException;
37 import freenet.keys.FreenetURI;
38
39 /**
40  * The Sone core.
41  *
42  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43  */
44 public class Core extends AbstractService {
45
46         /** The logger. */
47         private static final Logger logger = Logging.getLogger(Core.class);
48
49         /** The configuration. */
50         private Configuration configuration;
51
52         /** Interface to freenet. */
53         private FreenetInterface freenetInterface;
54
55         /** The local Sones. */
56         private final Set<Sone> localSones = new HashSet<Sone>();
57
58         /**
59          * Creates a new core.
60          */
61         public Core() {
62                 super("Sone Core");
63         }
64
65         //
66         // ACCESSORS
67         //
68
69         /**
70          * Sets the configuration of the core.
71          *
72          * @param configuration
73          *            The configuration of the core
74          * @return This core (for method chaining)
75          */
76         public Core configuration(Configuration configuration) {
77                 this.configuration = configuration;
78                 return this;
79         }
80
81         /**
82          * Sets the Freenet interface to use.
83          *
84          * @param freenetInterface
85          *            The Freenet interface to use
86          * @return This core (for method chaining)
87          */
88         public Core freenetInterface(FreenetInterface freenetInterface) {
89                 this.freenetInterface = freenetInterface;
90                 return this;
91         }
92
93         /**
94          * Returns the local Sones.
95          *
96          * @return The local Sones
97          */
98         public Set<Sone> localSones() {
99                 return localSones;
100         }
101
102         //
103         // ACTIONS
104         //
105
106         /**
107          * Creates a new Sone at a random location.
108          *
109          * @param name
110          *            The name of the Sone
111          * @return The created Sone
112          * @throws SoneException
113          *             if a Sone error occurs
114          */
115         public Sone createSone(String name) throws SoneException {
116                 return createSone(name, null, null);
117         }
118
119         /**
120          * Creates a new Sone at the given location. If one of {@code requestUri} or
121          * {@code insertUrI} is {@code null}, the Sone is created at a random
122          * location.
123          *
124          * @param name
125          *            The name of the Sone
126          * @param requestUri
127          *            The request URI of the Sone, or {@link NullPointerException}
128          *            to create a Sone at a random location
129          * @param insertUri
130          *            The insert URI of the Sone, or {@code null} to create a Sone
131          *            at a random location
132          * @return The created Sone
133          * @throws SoneException
134          *             if a Sone error occurs
135          */
136         public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
137                 if ((name == null) || (name.trim().length() == 0)) {
138                         throw new SoneException(Type.INVALID_SONE_NAME);
139                 }
140                 if ((requestUri == null) || (insertUri == null)) {
141                         String[] keyPair = freenetInterface.generateKeyPair();
142                         requestUri = keyPair[0];
143                         insertUri = keyPair[1];
144                 }
145                 Sone sone;
146                 try {
147                         logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, requestUri, insertUri });
148                         sone = new Sone(UUID.randomUUID(), name, new FreenetURI(requestUri), new FreenetURI(insertUri));
149                 } catch (MalformedURLException mue1) {
150                         throw new SoneException(Type.INVALID_URI);
151                 }
152                 localSones.add(sone);
153                 return sone;
154         }
155
156         //
157         // SERVICE METHODS
158         //
159
160         /**
161          * {@inheritDoc}
162          */
163         @Override
164         protected void serviceStart() {
165                 loadConfiguration();
166         }
167
168         /**
169          * {@inheritDoc}
170          */
171         @Override
172         protected void serviceStop() {
173                 saveConfiguration();
174         }
175
176         //
177         // PRIVATE METHODS
178         //
179
180         /**
181          * Loads the configuration.
182          */
183         private void loadConfiguration() {
184                 logger.entering(Core.class.getName(), "loadConfiguration()");
185
186                 /* get names of all local Sones. */
187                 String allSoneNamesString = configuration.getStringValue("Sone/Names").getValue(null);
188                 if (allSoneNamesString == null) {
189                         allSoneNamesString = "";
190                 }
191                 List<String> allSoneNames;
192                 try {
193                         allSoneNames = StringEscaper.parseLine(allSoneNamesString);
194                 } catch (TextException te1) {
195                         logger.log(Level.WARNING, "Could not parse Sone names: “" + allSoneNamesString + "”", te1);
196                         allSoneNames = Collections.emptyList();
197                 }
198
199                 /* parse local Sones. */
200                 logger.log(Level.INFO, "Loading %d Sones…", allSoneNames.size());
201                 for (String soneName : allSoneNames) {
202                         String id = configuration.getStringValue("Sone/Name." + soneName + "/ID").getValue(null);
203                         String insertUri = configuration.getStringValue("Sone/Name." + soneName + "/InsertURI").getValue(null);
204                         String requestUri = configuration.getStringValue("Sone/Name." + soneName + "/RequestURI").getValue(null);
205                         try {
206                                 localSones.add(new Sone(UUID.fromString(id), soneName, new FreenetURI(requestUri), new FreenetURI(insertUri)));
207                         } catch (MalformedURLException mue1) {
208                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
209                         }
210                 }
211
212                 logger.exiting(Core.class.getName(), "loadConfiguration()");
213         }
214
215         /**
216          * Saves the configuraiton.
217          */
218         private void saveConfiguration() {
219
220                 /* get the names of all Sones. */
221                 Set<String> soneNames = new HashSet<String>();
222                 for (Sone sone : localSones) {
223                         soneNames.add(sone.getName());
224                 }
225                 String soneNamesString = StringEscaper.escapeWords(soneNames);
226
227                 logger.log(Level.INFO, "Storing %d Sones…", soneNames.size());
228                 try {
229                         /* store names of all Sones. */
230                         configuration.getStringValue("Sone/Names").setValue(soneNamesString);
231
232                         /* store all Sones. */
233                         for (Sone sone : localSones) {
234                                 configuration.getStringValue("Sone/Name." + sone.getName() + "/ID").setValue(sone.getId());
235                                 configuration.getStringValue("Sone/Name." + sone.getName() + "/RequestURI").setValue(sone.getRequestUri().toString());
236                                 configuration.getStringValue("Sone/Name." + sone.getName() + "/InsertURI").setValue(sone.getInsertUri().toString());
237                         }
238                 } catch (ConfigurationException ce1) {
239                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
240                 }
241         }
242
243 }