Rename “localSones” method to a more traditional “getSones”.
[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> getSones() {
99                 return Collections.unmodifiableSet(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                 String finalRequestUri;
141                 String finalInsertUri;
142                 if ((requestUri == null) || (insertUri == null)) {
143                         String[] keyPair = freenetInterface.generateKeyPair();
144                         finalRequestUri = keyPair[0];
145                         finalInsertUri = keyPair[1];
146                 } else {
147                         finalRequestUri = requestUri;
148                         finalInsertUri = insertUri;
149                 }
150                 Sone sone;
151                 try {
152                         logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
153                         sone = new Sone(UUID.randomUUID(), name, new FreenetURI(finalRequestUri), new FreenetURI(finalInsertUri));
154                 } catch (MalformedURLException mue1) {
155                         throw new SoneException(Type.INVALID_URI);
156                 }
157                 localSones.add(sone);
158                 return sone;
159         }
160
161         /**
162          * Deletes the given Sone from this plugin instance.
163          *
164          * @param sone
165          *            The sone to delete
166          */
167         public void deleteSone(Sone sone) {
168                 localSones.remove(sone);
169         }
170
171         //
172         // SERVICE METHODS
173         //
174
175         /**
176          * {@inheritDoc}
177          */
178         @Override
179         protected void serviceStart() {
180                 loadConfiguration();
181         }
182
183         /**
184          * {@inheritDoc}
185          */
186         @Override
187         protected void serviceStop() {
188                 saveConfiguration();
189         }
190
191         //
192         // PRIVATE METHODS
193         //
194
195         /**
196          * Loads the configuration.
197          */
198         private void loadConfiguration() {
199                 logger.entering(Core.class.getName(), "loadConfiguration()");
200
201                 /* get names of all local Sones. */
202                 String allSoneNamesString = configuration.getStringValue("Sone/Names").getValue(null);
203                 if (allSoneNamesString == null) {
204                         allSoneNamesString = "";
205                 }
206                 List<String> allSoneNames;
207                 try {
208                         allSoneNames = StringEscaper.parseLine(allSoneNamesString);
209                 } catch (TextException te1) {
210                         logger.log(Level.WARNING, "Could not parse Sone names: “" + allSoneNamesString + "”", te1);
211                         allSoneNames = Collections.emptyList();
212                 }
213
214                 /* parse local Sones. */
215                 logger.log(Level.INFO, "Loading %d Sones…", allSoneNames.size());
216                 for (String soneName : allSoneNames) {
217                         String id = configuration.getStringValue("Sone/Name." + soneName + "/ID").getValue(null);
218                         String insertUri = configuration.getStringValue("Sone/Name." + soneName + "/InsertURI").getValue(null);
219                         String requestUri = configuration.getStringValue("Sone/Name." + soneName + "/RequestURI").getValue(null);
220                         try {
221                                 localSones.add(new Sone(UUID.fromString(id), soneName, new FreenetURI(requestUri), new FreenetURI(insertUri)));
222                         } catch (MalformedURLException mue1) {
223                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
224                         }
225                 }
226
227                 logger.exiting(Core.class.getName(), "loadConfiguration()");
228         }
229
230         /**
231          * Saves the configuraiton.
232          */
233         private void saveConfiguration() {
234
235                 /* get the names of all Sones. */
236                 Set<String> soneNames = new HashSet<String>();
237                 for (Sone sone : localSones) {
238                         soneNames.add(sone.getName());
239                 }
240                 String soneNamesString = StringEscaper.escapeWords(soneNames);
241
242                 logger.log(Level.INFO, "Storing %d Sones…", soneNames.size());
243                 try {
244                         /* store names of all Sones. */
245                         configuration.getStringValue("Sone/Names").setValue(soneNamesString);
246
247                         /* store all Sones. */
248                         for (Sone sone : localSones) {
249                                 configuration.getStringValue("Sone/Name." + sone.getName() + "/ID").setValue(sone.getId());
250                                 configuration.getStringValue("Sone/Name." + sone.getName() + "/RequestURI").setValue(sone.getRequestUri().toString());
251                                 configuration.getStringValue("Sone/Name." + sone.getName() + "/InsertURI").setValue(sone.getInsertUri().toString());
252                         }
253                 } catch (ConfigurationException ce1) {
254                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
255                 }
256         }
257
258 }