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