Don’t try to load properties for an empty list.
[demoscenemusic.git] / src / main / java / net / pterodactylus / demoscenemusic / data / DataManager.java
1 /*
2  * DemosceneMusic - DataManager.java - Copyright © 2012 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.demoscenemusic.data;
19
20 import java.sql.ResultSet;
21 import java.sql.SQLException;
22 import java.util.Collection;
23 import java.util.EnumMap;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Set;
30 import java.util.UUID;
31 import java.util.concurrent.Callable;
32
33 import net.pterodactylus.demoscenemusic.data.Track.Relationship;
34 import net.pterodactylus.util.collection.Memoizer;
35 import net.pterodactylus.util.database.Database;
36 import net.pterodactylus.util.database.DatabaseException;
37 import net.pterodactylus.util.database.Field;
38 import net.pterodactylus.util.database.Join;
39 import net.pterodactylus.util.database.Join.JoinType;
40 import net.pterodactylus.util.database.ObjectCreator;
41 import net.pterodactylus.util.database.ObjectCreator.StringCreator;
42 import net.pterodactylus.util.database.OrWhereClause;
43 import net.pterodactylus.util.database.OrderField;
44 import net.pterodactylus.util.database.Parameter.IntegerParameter;
45 import net.pterodactylus.util.database.Parameter.StringParameter;
46 import net.pterodactylus.util.database.Query;
47 import net.pterodactylus.util.database.Query.Type;
48 import net.pterodactylus.util.database.ResultProcessor;
49 import net.pterodactylus.util.database.ValueField;
50 import net.pterodactylus.util.database.ValueFieldWhereClause;
51
52 /**
53  * Interface between the database and the application.
54  *
55  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56  */
57 public class DataManager {
58
59         /** The artist object creator. */
60         @SuppressWarnings("synthetic-access")
61         private final ObjectCreator<Artist> artistCreator = new ArtistCreator();
62
63         /** The group object creator. */
64         @SuppressWarnings("synthetic-access")
65         private final ObjectCreator<Group> groupCreator = new GroupCreator();
66
67         /** The track object creator. */
68         @SuppressWarnings("synthetic-access")
69         private final ObjectCreator<Track> trackCreator = new TrackCreator();
70
71         /** The track object creator. */
72         @SuppressWarnings("synthetic-access")
73         private final ObjectCreator<TrackDerivative> trackDerivativeCreator = new TrackDerivativeCreator();
74
75         /** The style object creator. */
76         @SuppressWarnings("synthetic-access")
77         private final ObjectCreator<Style> styleCreator = new StyleCreator();
78
79         /** The party object creator. */
80         @SuppressWarnings("synthetic-access")
81         private final ObjectCreator<Party> partyCreator = new PartyCreator();
82
83         /** The {@link User} object creator. */
84         @SuppressWarnings("synthetic-access")
85         private final ObjectCreator<User> userCreator = new UserCreator();
86
87         /** The database. */
88         private final Database database;
89
90         /**
91          * Creates a new data manager.
92          *
93          * @param database
94          *            The database to operate on
95          */
96         public DataManager(Database database) {
97                 this.database = database;
98         }
99
100         /**
101          * Returns all artists.
102          *
103          * @return All artists
104          * @throws DatabaseException
105          *             if a database error occurs
106          */
107         public Collection<Artist> getAllArtists() throws DatabaseException {
108                 Query query = new Query(Type.SELECT, "ARTISTS");
109                 query.addField(new Field("ARTISTS.*"));
110                 return loadArtistProperties(database.getMultiple(query, artistCreator));
111         }
112
113         /**
114          * Returns the artist with the given ID.
115          *
116          * @param id
117          *            The ID of the artist
118          * @return The artist with the given ID, or {@code null} if there is no
119          *         artist with the given ID
120          * @throws DatabaseException
121          *             if a database error occurs
122          */
123         public Artist getArtistById(String id) throws DatabaseException {
124                 Query query = new Query(Type.SELECT, "ARTISTS");
125                 query.addField(new Field("ARTISTS.*"));
126                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("ARTISTS.ID", new StringParameter(id))));
127                 return loadArtistProperties(database.getSingle(query, artistCreator));
128         }
129
130         /**
131          * Returns all artists that belong to the group with the given ID.
132          *
133          * @param groupId
134          *            The ID of the group
135          * @return All artists belonging to the given group
136          * @throws DatabaseException
137          *             if a database error occurs
138          */
139         public Collection<Artist> getArtistsByGroup(String groupId) throws DatabaseException {
140                 Query query = new Query(Type.SELECT, "ARTISTS");
141                 query.addField(new Field("ARTISTS.*"));
142                 query.addJoin(new Join(JoinType.INNER, "GROUP_ARTISTS", new Field("ARTISTS.ID"), new Field("GROUP_ARTISTS.ARTIST")));
143                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUP_ARTISTS.GROUP_", new StringParameter(groupId))));
144                 return loadArtistProperties(database.getMultiple(query, artistCreator));
145         }
146
147         /**
148          * Returns all artists involved in the track with the given ID.
149          *
150          * @param trackId
151          *            The ID of the track
152          * @return All artists involved in the track, in preferred order
153          * @throws DatabaseException
154          *             if a database error occurs
155          */
156         public List<Artist> getArtistsByTrack(String trackId) throws DatabaseException {
157                 Query query = new Query(Type.SELECT, "ARTISTS");
158                 query.addField(new Field("ARTISTS.*"));
159                 query.addJoin(new Join(JoinType.INNER, "TRACK_ARTISTS", new Field("TRACK_ARTISTS.ARTIST"), new Field("ARTISTS.ID")));
160                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_ARTISTS.TRACK", new StringParameter(trackId))));
161                 query.addOrderField(new OrderField(new Field("TRACK_ARTISTS.DISPLAY_ORDER")));
162                 return loadArtistProperties(database.getMultiple(query, artistCreator));
163         }
164
165         /**
166          * Creates a new artist with the given name.
167          *
168          * @param name
169          *            The name of the artist
170          * @return The created artist
171          * @throws DatabaseException
172          *             if a database error occurs
173          */
174         public Artist createArtist(String name) throws DatabaseException {
175                 Query query = new Query(Type.INSERT, "ARTISTS");
176                 String id = UUID.randomUUID().toString();
177                 query.addValueField(new ValueField("ID", new StringParameter(id)));
178                 query.addValueField(new ValueField("NAME", new StringParameter(name)));
179                 database.insert(query);
180                 return loadArtistProperties(getArtistById(id));
181         }
182
183         /**
184          * Saves the given artist.
185          *
186          * @param artist
187          *            The artist to save
188          * @throws DatabaseException
189          *             if a database error occurs
190          */
191         public void saveArtist(Artist artist) throws DatabaseException {
192                 Query query = new Query(Type.UPDATE, "ARTISTS");
193                 query.addValueField(new ValueField("NAME", new StringParameter(artist.getName())));
194                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("ID", new StringParameter(artist.getId()))));
195                 database.update(query);
196
197                 /* save groups. */
198                 Collection<Group> groups = artist.getGroups();
199                 query = new Query(Type.DELETE, "GROUP_ARTISTS");
200                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUP_ARTISTS.ARTIST", new StringParameter(artist.getId()))));
201                 database.update(query);
202                 for (Group group : groups) {
203                         query = new Query(Type.INSERT, "GROUP_ARTISTS");
204                         query.addValueField(new ValueField("GROUP_", new StringParameter(group.getId())));
205                         query.addValueField(new ValueField("ARTIST", new StringParameter(artist.getId())));
206                         database.insert(query);
207                 }
208
209                 /* save properties. */
210                 saveArtistProperties(artist);
211         }
212
213         /**
214          * Saves the properties of the given artist.
215          *
216          * @param artist
217          *            The artist whose properties to save
218          * @throws DatabaseException
219          *             if a database error occurs
220          */
221         public void saveArtistProperties(Artist artist) throws DatabaseException {
222                 saveProperties(artist.getProperties(), "ARTIST_PROPERTIES", "ARTIST", artist.getId());
223         }
224
225         /**
226          * Saves the given properties to the given table for the given principal.
227          *
228          * @param properties
229          *            The properties to save
230          * @param table
231          *            The table in which to save the properties
232          * @param type
233          *            The type of the principal (e. g. “ARTIST” or “TRACK”)
234          * @param id
235          *            The ID of the principial
236          * @throws DatabaseException
237          *             if a database error occurs
238          */
239         public void saveProperties(Properties properties, String table, String type, String id) throws DatabaseException {
240                 if (!properties.isDirty()) {
241                         return;
242                 }
243                 Query query = new Query(Type.DELETE, table);
244                 query.addWhereClause(new ValueFieldWhereClause(new ValueField(type, new StringParameter(id))));
245                 database.update(query);
246                 for (Entry<String, String> property : properties) {
247                         Query insertQuery = new Query(Type.INSERT, table);
248                         insertQuery.addValueField(new ValueField(type, new StringParameter(id)));
249                         insertQuery.addValueField(new ValueField("PROPERTY", new StringParameter(property.getKey())));
250                         insertQuery.addValueField(new ValueField("VALUE", new StringParameter(property.getValue())));
251                         database.insert(insertQuery);
252                 }
253                 properties.resetDirty();
254         }
255
256         /**
257          * Loads the properties for an artist.
258          *
259          * @param artist
260          *            The artist to load the properties for
261          * @return The artist
262          * @throws DatabaseException
263          *             if a database error occurs
264          */
265         public Artist loadArtistProperties(final Artist artist) throws DatabaseException {
266                 return loadProperties(artist, "ARTIST_PROPERTIES", "ARTIST");
267         }
268
269         /**
270          * Loads the properties of all given artists.
271          *
272          * @param artists
273          *            The artists to load the properties for
274          * @return The list of artists
275          * @throws DatabaseException
276          *             if a database error occurs
277          */
278         public List<Artist> loadArtistProperties(List<Artist> artists) throws DatabaseException {
279                 return loadProperties(artists, "ARTIST_PROPERTIES", "ARTIST");
280         }
281
282         /**
283          * Returns all remix artists involved in the track with the given ID.
284          *
285          * @param trackId
286          *            The ID of the track
287          * @return All remix artists involved in the track, in preferred order
288          * @throws DatabaseException
289          *             if a database error occurs
290          */
291         public List<Artist> getRemixArtistsByTrack(String trackId) throws DatabaseException {
292                 Query query = new Query(Type.SELECT, "ARTISTS");
293                 query.addField(new Field("ARTISTS.*"));
294                 query.addJoin(new Join(JoinType.INNER, "TRACK_REMIX_ARTISTS", new Field("TRACK_REMIX_ARTISTS.ARTIST"), new Field("ARTISTS.ID")));
295                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_REMIX_ARTISTS.TRACK", new StringParameter(trackId))));
296                 query.addOrderField(new OrderField(new Field("TRACK_REMIX_ARTISTS.DISPLAY_ORDER")));
297                 return database.getMultiple(query, artistCreator);
298         }
299
300         /**
301          * Returns all related tracks for the track with the given ID.
302          *
303          * @param trackId
304          *            The ID of the tracks
305          * @return A mapping from relationship to all tracks that match the relation
306          * @throws DatabaseException
307          *             if a database error occurs
308          */
309         public Map<Relationship, Collection<Track>> getRelatedTracksByTrack(String trackId) throws DatabaseException {
310                 Query query = new Query(Type.SELECT, "TRACKS");
311                 query.addField(new Field("TRACKS.*"));
312                 query.addField(new Field("TRACK_RELATIONS.*"));
313                 query.addJoin(new Join(JoinType.INNER, "TRACK_RELATIONS", new Field("TRACK_RELATIONS.TRACK"), new Field("TRACK_RELATIONS.RELATED_TRACK")));
314                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_RELATIONS.TRACK", new StringParameter(trackId))));
315                 final Map<Relationship, Collection<Track>> relatedTracks = new EnumMap<Relationship, Collection<Track>>(Relationship.class);
316                 database.process(query, new ResultProcessor() {
317
318                         @Override
319                         @SuppressWarnings("synthetic-access")
320                         public void processResult(ResultSet resultSet) throws SQLException {
321                                 Track track = trackCreator.createObject(resultSet);
322                                 Relationship relationship = Relationship.valueOf(resultSet.getString("TRACK_RELATIONS.RELATIONSHIP"));
323                                 if (!relatedTracks.containsKey(relationship)) {
324                                         relatedTracks.put(relationship, new HashSet<Track>());
325                                 }
326                                 relatedTracks.get(relationship).add(track);
327                         }
328                 });
329                 return relatedTracks;
330         }
331
332         /**
333          * Returns the track with the given ID.
334          *
335          * @param id
336          *            The ID of the track
337          * @return The track with the given ID, or {@code null} if there is no such
338          *         track
339          * @throws DatabaseException
340          *             if a database error occurs
341          */
342         public Track getTrackById(String id) throws DatabaseException {
343                 Query query = new Query(Type.SELECT, "TRACKS");
344                 query.addField(new Field("TRACKS.*"));
345                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACKS.ID", new StringParameter(id))));
346                 return loadTrackProperties(database.getSingle(query, trackCreator));
347         }
348
349         /**
350          * Returns the track that contains the derivative with the given ID.
351          *
352          * @param id
353          *            The ID of the track derivative
354          * @return The track the derivative belongs to, or {@code null} if there is
355          *         no such track
356          * @throws DatabaseException
357          *             if a database error occurs
358          */
359         public Track getTrackByDerivativeId(String id) throws DatabaseException {
360                 Query query = new Query(Type.SELECT, "TRACKS");
361                 query.addField(new Field("TRACKS.*"));
362                 query.addJoin(new Join(JoinType.INNER, "TRACK_DERIVATIVES", new Field("TRACK_DERIVATIVES.TRACK"), new Field("TRACKS.ID")));
363                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_DERIVATIVES.ID", new StringParameter(id))));
364                 return loadTrackProperties(database.getSingle(query, trackCreator));
365         }
366
367         /**
368          * Returns all tracks by the artist with the given ID.
369          *
370          * @param artistId
371          *            The ID of the artist
372          * @return All tracks by the given artist
373          * @throws DatabaseException
374          *             if a database error occurs
375          */
376         public Collection<Track> getTracksByArtist(String artistId) throws DatabaseException {
377                 Query query = new Query(Type.SELECT, "TRACKS");
378                 query.addField(new Field("TRACKS.*"));
379                 query.addJoin(new Join(JoinType.INNER, "TRACK_ARTISTS", new Field("TRACKS.ID"), new Field("TRACK_ARTISTS.TRACK")));
380                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_ARTISTS.ARTIST", new StringParameter(artistId))));
381                 return loadTrackProperties(database.getMultiple(query, trackCreator));
382         }
383
384         /**
385          * Returns all tracks that were released at the party with the given ID.
386          *
387          * @param partyId
388          *            The ID of the party
389          * @return All tracks that were released at the given party
390          * @throws DatabaseException
391          *             if a database error occurs
392          */
393         public Collection<Track> getTracksByParty(String partyId) throws DatabaseException {
394                 Query query = new Query(Type.SELECT, "TRACKS");
395                 query.addField(new Field("TRACKS.*"));
396                 query.addJoin(new Join(JoinType.INNER, "PARTY_TRACKS", new Field("PARTY_TRACKS.TRACK"), new Field("TRACKS.ID")));
397                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("PARTY_TRACKS.PARTY", new StringParameter(partyId))));
398                 return loadTrackProperties(database.getMultiple(query, trackCreator));
399         }
400
401         /**
402          * Loads the properties for the given track.
403          *
404          * @param track
405          *            The track for which to load the properties
406          * @return The track with the properties loaded
407          * @throws DatabaseException
408          *             if a database error occurs
409          */
410         public Track loadTrackProperties(Track track) throws DatabaseException {
411                 return loadProperties(track, "TRACK_PROPERTIES", "TRACK");
412         }
413
414         /**
415          * Loads the properties for the given tracks.
416          *
417          * @param tracks
418          *            The tracks for which to load the properties
419          * @return The tracks with the properties loaded
420          * @throws DatabaseException
421          *             if a database error occurs
422          */
423         public List<Track> loadTrackProperties(List<Track> tracks) throws DatabaseException {
424                 return loadProperties(tracks, "TRACK_PROPERTIES", "TRACK");
425         }
426
427         /**
428          * Creates a new track with the given name.
429          *
430          * @param name
431          *            The name of the track
432          * @return The created track
433          * @throws DatabaseException
434          *             if a database error occurs
435          */
436         public Track createTrack(String name) throws DatabaseException {
437                 Query query = new Query(Type.INSERT, "TRACKS");
438                 String id = UUID.randomUUID().toString();
439                 query.addValueField(new ValueField("ID", new StringParameter(id)));
440                 query.addValueField(new ValueField("NAME", new StringParameter(name)));
441                 database.insert(query);
442                 return getTrackById(id);
443         }
444
445         /**
446          * Saves the given track. This also saves all relationships of the track.
447          *
448          * @param track
449          *            The track to save
450          * @throws DatabaseException
451          *             if a database error occurs
452          */
453         public void saveTrack(Track track) throws DatabaseException {
454                 Query query = new Query(Type.UPDATE, "TRACKS");
455                 query.addValueField(new ValueField("TRACKS.NAME", new StringParameter(track.getName())));
456                 query.addValueField(new ValueField("TRACKS.REMIX", new StringParameter(track.getRemix())));
457                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACKS.ID", new StringParameter(track.getId()))));
458                 database.update(query);
459                 /* store artist information. */
460                 track.getArtists(); /* prefetch artists. */
461                 query = new Query(Type.DELETE, "TRACK_ARTISTS");
462                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_ARTISTS.TRACK", new StringParameter(track.getId()))));
463                 database.update(query);
464                 for (int index = 0; index < track.getArtists().size(); ++index) {
465                         query = new Query(Type.INSERT, "TRACK_ARTISTS");
466                         query.addValueField(new ValueField("TRACK_ARTISTS.TRACK", new StringParameter(track.getId())));
467                         query.addValueField(new ValueField("TRACK_ARTISTS.ARTIST", new StringParameter(track.getArtists().get(index).getId())));
468                         query.addValueField(new ValueField("TRACK_ARTISTS.DISPLAY_ORDER", new IntegerParameter(index + 1)));
469                         database.insert(query);
470                 }
471
472                 /* store party links. */
473                 Collection<Party> parties = track.getParties(); /* prefetch parties. */
474                 query = new Query(Type.DELETE, "PARTY_TRACKS");
475                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("PARTY_TRACKS.TRACK", new StringParameter(track.getId()))));
476                 database.update(query);
477                 for (Party party : parties) {
478                         query = new Query(Type.INSERT, "PARTY_TRACKS");
479                         query.addValueField(new ValueField("PARTY_TRACKS.TRACK", new StringParameter(track.getId())));
480                         query.addValueField(new ValueField("PARTY_TRACKS.PARTY", new StringParameter(party.getId())));
481                         database.insert(query);
482                 }
483
484                 /* store properties. */
485                 saveProperties(track.getProperties(), "TRACK_PROPERTIES", "TRACK", track.getId());
486         }
487
488         /**
489          * Returns the derivative with the given ID.
490          *
491          * @param id
492          *            The ID of the derivatives to load
493          * @return The derivative with the given ID
494          * @throws DatabaseException
495          *             if a database error occurs
496          */
497         public TrackDerivative getTrackDerivativeById(String id) throws DatabaseException {
498                 Query query = new Query(Type.SELECT, "TRACK_DERIVATIVES");
499                 query.addField(new Field("TRACK_DERIVATIVES.*"));
500                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_DERIVATIVES.ID", new StringParameter(id))));
501                 return loadTrackDerivativeProperties(database.getSingle(query, trackDerivativeCreator));
502         }
503
504         /**
505          * Returns the derivatives for the given track.
506          *
507          * @param trackId
508          *            The track ID to get the derivatives for
509          * @return The derivatives for the given track
510          * @throws DatabaseException
511          *             if a database error occurs
512          */
513         public Collection<TrackDerivative> getTrackDerivativesByTrack(String trackId) throws DatabaseException {
514                 Query query = new Query(Type.SELECT, "TRACK_DERIVATIVES");
515                 query.addField(new Field("TRACK_DERIVATIVES.*"));
516                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_DERIVATIVES.TRACK", new StringParameter(trackId))));
517                 return loadTrackDerivativeProperties(database.getMultiple(query, trackDerivativeCreator));
518         }
519
520         /**
521          * Creates a new derivative for the given track.
522          *
523          * @param track
524          *            The track to create the derivative for
525          * @return The created derivative
526          * @throws DatabaseException
527          *             if a database error occurs
528          */
529         public TrackDerivative createTrackDerivative(Track track) throws DatabaseException {
530                 Query query = new Query(Type.INSERT, "TRACK_DERIVATIVES");
531                 String id = UUID.randomUUID().toString();
532                 query.addValueField(new ValueField("TRACK_DERIVATIVES.ID", new StringParameter(id)));
533                 query.addValueField(new ValueField("TRACK_DERIVATIVES.TRACK", new StringParameter(track.getId())));
534                 database.insert(query);
535                 return getTrackDerivativeById(id);
536         }
537
538         /**
539          * Loads the properties for the given track derivative.
540          *
541          * @param trackDerivative
542          *            The track derivative to load the properties for
543          * @return The track derivative with its properties loaded
544          * @throws DatabaseException
545          *             if a database error occurs
546          */
547         public TrackDerivative loadTrackDerivativeProperties(TrackDerivative trackDerivative) throws DatabaseException {
548                 return loadProperties(trackDerivative, "TRACK_DERIVATIVE_PROPERTIES", "TRACK_DERIVATIVE");
549         }
550
551         /**
552          * Loads the properties for the given track derivatives.
553          *
554          * @param trackDerivatives
555          *            The track derivatives to load the properties for
556          * @return The track derivatives with their properties loaded
557          * @throws DatabaseException
558          *             if a database error occurs
559          */
560         public List<TrackDerivative> loadTrackDerivativeProperties(List<TrackDerivative> trackDerivatives) throws DatabaseException {
561                 return loadProperties(trackDerivatives, "TRACK_DERIVATIVE_PROPERTIES", "TRACK_DERIVATIVE");
562         }
563
564         /**
565          * Saves the given track derivative. As a track derivative does not have any
566          * attributes of its own only its properties are saved.
567          *
568          * @param trackDerivative
569          *            The track derivative to save
570          * @throws DatabaseException
571          *             if a database error occurs
572          */
573         public void saveTrackDerivate(TrackDerivative trackDerivative) throws DatabaseException {
574                 saveProperties(trackDerivative.getProperties(), "TRACK_DERIVATIVE_PROPERTIES", "TRACK_DERIVATIVE", trackDerivative.getId());
575         }
576
577         /**
578          * Removes the given track derivative and all its properties from the
579          * database.
580          *
581          * @param trackDerivative
582          *            The track derivative to remove
583          * @throws DatabaseException
584          *             if a database error occurs
585          */
586         public void removeTrackDerivative(TrackDerivative trackDerivative) throws DatabaseException {
587                 Query query = new Query(Type.DELETE, "TRACK_DERIVATIVES");
588                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_DERIVATIVES.ID", new StringParameter(trackDerivative.getId()))));
589                 database.update(query);
590                 /* remove the properties. */
591                 saveProperties(new Properties().set("dirty", "true").removeAll(), "TRACK_DERIVATIVE_PROPERTIES", "TRACK_DERIVATIVE", trackDerivative.getId());
592         }
593
594         /**
595          * Returns all groups.
596          *
597          * @return All groups
598          * @throws DatabaseException
599          *             if a database error occurs
600          */
601         public Collection<Group> getAllGroups() throws DatabaseException {
602                 Query query = new Query(Type.SELECT, "GROUPS");
603                 query.addField(new Field("GROUPS.*"));
604                 return loadGroupProperties(database.getMultiple(query, groupCreator));
605         }
606
607         /**
608          * Returns the group with the given ID.
609          *
610          * @param groupId
611          *            The ID of the group
612          * @return The group with the given ID, or {@code null} if no such group
613          *         exists
614          * @throws DatabaseException
615          *             if a database error occurs
616          */
617         public Group getGroupById(String groupId) throws DatabaseException {
618                 Query query = new Query(Type.SELECT, "GROUPS");
619                 query.addField(new Field("GROUPS.*"));
620                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUPS.ID", new StringParameter(groupId))));
621                 return loadGroupProperties(database.getSingle(query, groupCreator));
622         }
623
624         /**
625          * Returns all groups the artist with the given ID belongs to.
626          *
627          * @param artistId
628          *            The ID of the artist
629          * @return All groups the artist belongs to
630          * @throws DatabaseException
631          *             if a database error occurs
632          */
633         public Collection<Group> getGroupsByArtist(String artistId) throws DatabaseException {
634                 Query query = new Query(Type.SELECT, "GROUPS");
635                 query.addField(new Field("GROUPS.*"));
636                 query.addJoin(new Join(JoinType.INNER, "GROUP_ARTISTS", new Field("GROUPS.ID"), new Field("GROUP_ARTISTS.GROUP_")));
637                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUP_ARTISTS.ARTIST", new StringParameter(artistId))));
638                 return database.getMultiple(query, groupCreator);
639         }
640
641         /**
642          * Loads the properties of the given group.
643          *
644          * @param group
645          *            The group to load the properties for
646          * @return The group with its properties loaded
647          * @throws DatabaseException
648          *             if a database error occurs
649          */
650         public Group loadGroupProperties(Group group) throws DatabaseException {
651                 return loadProperties(group, "GROUP_PROPERTIES", "GROUP_ID");
652         }
653
654         /**
655          * Loads the properties of the given groups.
656          *
657          * @param groups
658          *            The groups to load the properties for
659          * @return The groups with their properties loaded
660          * @throws DatabaseException
661          *             if a database error occurs
662          */
663         public Collection<Group> loadGroupProperties(List<Group> groups) throws DatabaseException {
664                 return loadProperties(groups, "GROUP_PROPERTIES", "GROUP_ID");
665         }
666
667         /**
668          * Creates a group with the given name.
669          *
670          * @param name
671          *            The name of the new group
672          * @return The new group
673          * @throws DatabaseException
674          *             if a database error occurs
675          */
676         public Group createGroup(String name) throws DatabaseException {
677                 Query query = new Query(Type.INSERT, "GROUPS");
678                 String id = UUID.randomUUID().toString();
679                 query.addValueField(new ValueField("ID", new StringParameter(id)));
680                 query.addValueField(new ValueField("NAME", new StringParameter(name)));
681                 database.insert(query);
682                 return getGroupById(id);
683         }
684
685         /**
686          * Saves the given group.
687          *
688          * @param group
689          *            The group to save
690          * @throws DatabaseException
691          *             if a database error occurs
692          */
693         public void saveGroup(Group group) throws DatabaseException {
694                 Query query = new Query(Type.UPDATE, "GROUPS");
695                 query.addValueField(new ValueField("NAME", new StringParameter(group.getName())));
696                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("ID", new StringParameter(group.getId()))));
697                 database.update(query);
698                 /* save properties. */
699                 saveGroupProperties(group);
700         }
701
702         /**
703          * Saves the properties of the given group.
704          *
705          * @param group
706          *            The group whose properties to save
707          * @throws DatabaseException
708          *             if a database error occurs
709          */
710         public void saveGroupProperties(Group group) throws DatabaseException {
711                 saveProperties(group.getProperties(), "GROUP_PROPERTIES", "GROUP_ID", group.getId());
712         }
713
714         /**
715          * Returns all styles for the track with the given ID.
716          *
717          * @param trackId
718          *            The ID of the track
719          * @return All styles for the given track
720          * @throws DatabaseException
721          *             if a database error occurs
722          */
723         public Collection<Style> getStylesByTrack(String trackId) throws DatabaseException {
724                 Query query = new Query(Type.SELECT, "STYLES");
725                 query.addField(new Field("STYLES.*"));
726                 query.addJoin(new Join(JoinType.INNER, "TRACK_STYLES", new Field("STYLES.ID"), new Field("TRACK_STYLES.STYLE")));
727                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_STYLES.TRACK", new StringParameter(trackId))));
728                 return database.getMultiple(query, styleCreator);
729         }
730
731         /**
732          * Returns all parties.
733          *
734          * @return All parties
735          * @throws DatabaseException
736          *             if a database error occurs
737          */
738         public Collection<Party> getAllParties() throws DatabaseException {
739                 Query query = new Query(Type.SELECT, "PARTIES");
740                 query.addField(new Field("PARTIES.*"));
741                 return loadPartyProperties(database.getMultiple(query, partyCreator));
742         }
743
744         /**
745          * Returns all parties that the track with the given ID was released at.
746          *
747          * @param trackId
748          *            The ID of the track
749          * @return All parties the track was released at
750          * @throws DatabaseException
751          *             if a database error occurs
752          */
753         public Collection<Party> getPartiesByTrackId(String trackId) throws DatabaseException {
754                 Query query = new Query(Type.SELECT, "PARTIES");
755                 query.addField(new Field("PARTIES.*"));
756                 query.addJoin(new Join(JoinType.INNER, "PARTY_TRACKS", new Field("PARTY_TRACKS.PARTY"), new Field("PARTIES.ID")));
757                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("PARTY_TRACKS.TRACK", new StringParameter(trackId))));
758                 return loadPartyProperties(database.getMultiple(query, partyCreator));
759         }
760
761         /**
762          * Returns the party with the given ID.
763          *
764          * @param partyId
765          *            The ID of the party
766          * @return The party with the given ID
767          * @throws DatabaseException
768          *             if a database error occurs
769          */
770         public Party getPartyById(String partyId) throws DatabaseException {
771                 Query query = new Query(Type.SELECT, "PARTIES");
772                 query.addField(new Field("PARTIES.*"));
773                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("PARTIES.ID", new StringParameter(partyId))));
774                 return loadPartyProperties(database.getSingle(query, partyCreator));
775         }
776
777         /**
778          * Loads the properties of the given party.
779          *
780          * @param party
781          *            The party to load the properties for
782          * @return The party with its properties loaded
783          * @throws DatabaseException
784          *             if a database error occurs
785          */
786         public Party loadPartyProperties(Party party) throws DatabaseException {
787                 return loadProperties(party, "PARTY_PROPERTIES", "PARTY");
788         }
789
790         /**
791          * Loads the properties of the given parties.
792          *
793          * @param parties
794          *            The parties to load the properties for
795          * @return The parties with their properties loaded
796          * @throws DatabaseException
797          *             if a database error occurs
798          */
799         public List<Party> loadPartyProperties(List<Party> parties) throws DatabaseException {
800                 return loadProperties(parties, "PARTY_PROPERTIES", "PARTY");
801         }
802
803         /**
804          * Saves the given party.
805          *
806          * @param party
807          *            The party to save
808          * @throws DatabaseException
809          *             if a database error occurs
810          */
811         public void saveParty(Party party) throws DatabaseException {
812                 Query query = new Query(Type.UPDATE, "PARTIES");
813                 query.addValueField(new ValueField("NAME", new StringParameter(party.getName())));
814                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("ID", new StringParameter(party.getId()))));
815                 database.update(query);
816                 savePartyProperties(party);
817         }
818
819         /**
820          * Saves the properties of the given party.
821          *
822          * @param party
823          *            The party whose properties to save
824          * @throws DatabaseException
825          *             if a database error occurs
826          */
827         public void savePartyProperties(Party party) throws DatabaseException {
828                 saveProperties(party.getProperties(), "PARTY_PROPERTIES", "PARTY", party.getId());
829         }
830
831         /**
832          * Creates a new party with the given name.
833          *
834          * @param name
835          *            The name of the party
836          * @return The new party
837          * @throws DatabaseException
838          *             if a database error occurs
839          */
840         public Party createParty(String name) throws DatabaseException {
841                 Query query = new Query(Type.INSERT, "PARTIES");
842                 String id = UUID.randomUUID().toString();
843                 query.addValueField(new ValueField("ID", new StringParameter(id)));
844                 query.addValueField(new ValueField("NAME", new StringParameter(name)));
845                 database.insert(query);
846                 return getPartyById(id);
847         }
848
849         /**
850          * Returns the user with the given name.
851          *
852          * @param username
853          *            The name of the user
854          * @return The user, or {@code null} if the user does not exist
855          * @throws DatabaseException
856          *             if a database error occurs
857          */
858         public User getUserByName(String username) throws DatabaseException {
859                 Query query = new Query(Type.SELECT, "USERS");
860                 query.addField(new Field("USERS.*"));
861                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USERS.NAME", new StringParameter(username))));
862                 return database.getSingle(query, userCreator);
863         }
864
865         /**
866          * Returns the user connected with the given OpenID.
867          *
868          * @param openId
869          *            The OpenID to find the user for
870          * @return The user connected with the given OpenID, or {@code null} if
871          *         there is no such user
872          * @throws DatabaseException
873          *             if a database error occurs
874          */
875         public User getUserByOpenId(String openId) throws DatabaseException {
876                 Query query = new Query(Type.SELECT, "USERS");
877                 query.addField(new Field("USERS.*"));
878                 query.addJoin(new Join(JoinType.INNER, "USER_OPENIDS", new Field("USER_OPENIDS.USER"), new Field("USERS.ID")));
879                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.OPENID", new StringParameter(openId))));
880                 return database.getSingle(query, userCreator);
881         }
882
883         /**
884          * Returns all OpenIDs connected with the user with the given ID.
885          *
886          * @param userId
887          *            The ID of the user
888          * @return All OpenIDs connected with the given user
889          * @throws DatabaseException
890          *             if a database error occurs
891          */
892         public Collection<String> getOpenIdsByUser(String userId) throws DatabaseException {
893                 Query query = new Query(Type.SELECT, "USER_OPENIDS");
894                 query.addField(new Field("USER_OPENIDS.*"));
895                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.USER", new StringParameter(userId))));
896                 return database.getMultiple(query, new StringCreator("USER_OPENIDS.OPENID"));
897         }
898
899         //
900         // PRIVATE METHODS
901         //
902
903         /**
904          * Loads the properties for the given object.
905          *
906          * @param <T>
907          *            The type of the object
908          * @param object
909          *            The object
910          * @param table
911          *            The table to load the properties from
912          * @param type
913          *            The type of the object (“ARTIST,” “TRACK,” etc.)
914          * @return The object with its properties loaded
915          * @throws DatabaseException
916          *             if a database error occurs
917          */
918         private <T extends Base> T loadProperties(final T object, final String table, String type) throws DatabaseException {
919                 if (object == null) {
920                         return null;
921                 }
922                 Query query = new Query(Type.SELECT, table);
923                 query.addField(new Field(table + ".PROPERTY"));
924                 query.addField(new Field(table + ".VALUE"));
925                 query.addWhereClause(new ValueFieldWhereClause(new ValueField(type, new StringParameter(object.getId()))));
926                 database.process(query, new ResultProcessor() {
927
928                         @Override
929                         public void processResult(ResultSet resultSet) throws SQLException {
930                                 if (resultSet.isFirst()) {
931                                         object.getProperties().removeAll();
932                                 }
933                                 object.getProperties().set(resultSet.getString(table + ".PROPERTY"), resultSet.getString(table + ".VALUE"));
934                         }
935
936                 });
937                 return object;
938         }
939
940         /**
941          * Loads the properties for the given objects.
942          *
943          * @param <T>
944          *            The type of the object
945          * @param objects
946          *            The objects
947          * @param table
948          *            The table to load the properties from
949          * @param type
950          *            The type of the object (“ARTIST,” “TRACK,” etc.)
951          * @return The object with its properties loaded
952          * @throws DatabaseException
953          *             if a database error occurs
954          */
955         private <T extends Base> List<T> loadProperties(List<T> objects, final String table, final String type) throws DatabaseException {
956                 if (objects.isEmpty()) {
957                         return objects;
958                 }
959                 final Map<String, T> objectMap = new HashMap<String, T>();
960                 final Set<String> firstObjects = new HashSet<String>();
961                 for (T object : objects) {
962                         objectMap.put(object.getId(), object);
963                         firstObjects.add(object.getId());
964                 }
965                 Query query = new Query(Type.SELECT, table);
966                 query.addField(new Field(table + "." + type));
967                 query.addField(new Field(table + ".PROPERTY"));
968                 query.addField(new Field(table + ".VALUE"));
969                 OrWhereClause whereClause = new OrWhereClause();
970                 for (T object : objects) {
971                         whereClause.add(new ValueFieldWhereClause(new ValueField(type, new StringParameter(object.getId()))));
972                 }
973                 query.addWhereClause(whereClause);
974                 database.process(query, new ResultProcessor() {
975
976                         @Override
977                         public void processResult(ResultSet resultSet) throws SQLException {
978                                 String id = resultSet.getString(table + "." + type);
979                                 T object = objectMap.get(id);
980                                 if (firstObjects.remove(id)) {
981                                         object.getProperties().removeAll();
982                                 }
983                                 object.getProperties().set(resultSet.getString(table + ".PROPERTY"), resultSet.getString(table + ".VALUE"));
984                         }
985
986                 });
987                 return objects;
988         }
989
990         /**
991          * {@link Artist} implementation that retrieves some attributes (such as
992          * {@link #getGroups()}, and {@link #getTracks()}) from the
993          * {@link DataManager} on demand.
994          *
995          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
996          */
997         private class LazyArtist extends DefaultArtist {
998
999                 /** Memoizer for the tracks by this artist. */
1000                 private final Memoizer<Void> tracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
1001
1002                         @Override
1003                         public Void call() throws DatabaseException {
1004                                 if (!hasValue("tracks")) {
1005                                         getValue("tracks", Collection.class).set(getTracksByArtist(getId()));
1006                                 }
1007                                 return null;
1008                         }
1009                 });
1010
1011                 /** Memoizer for the groups of this artist. */
1012                 private final Memoizer<Void> groupsMemoizer = new Memoizer<Void>(new Callable<Void>() {
1013
1014                         @Override
1015                         public Void call() throws Exception {
1016                                 if (!hasValue("groups")) {
1017                                         getValue("groups", Collection.class).set(getGroupsByArtist(getId()));
1018                                 }
1019                                 return null;
1020                         }
1021
1022                 });
1023
1024                 /**
1025                  * Creates a new lazy artist.
1026                  *
1027                  * @param id
1028                  *            The ID of the artist
1029                  */
1030                 public LazyArtist(String id) {
1031                         super(id);
1032                 }
1033
1034                 //
1035                 // DEFAULTARTIST METHODS
1036                 //
1037
1038                 /**
1039                  * {@inheritDoc}
1040                  */
1041                 @Override
1042                 public Collection<Group> getGroups() {
1043                         groupsMemoizer.get();
1044                         return super.getGroups();
1045                 }
1046
1047                 /**
1048                  * {@inheritDoc}
1049                  */
1050                 @Override
1051                 public Collection<Track> getTracks() {
1052                         tracksMemoizer.get();
1053                         return super.getTracks();
1054                 }
1055
1056         }
1057
1058         /**
1059          * {@link ObjectCreator} implementation that can create {@link Artist}
1060          * objects. This specific class actually creates {@link LazyArtist}
1061          * instances.
1062          *
1063          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1064          */
1065         private class ArtistCreator implements ObjectCreator<Artist> {
1066
1067                 /**
1068                  * {@inheritDoc}
1069                  */
1070                 @Override
1071                 public Artist createObject(ResultSet resultSet) throws SQLException {
1072                         return new LazyArtist(resultSet.getString("ARTISTS.ID")).setName(resultSet.getString("ARTISTS.NAME"));
1073                 }
1074
1075         }
1076
1077         /**
1078          * {@link Group} implementation that retrieves some attributes (such as
1079          * {@link #getArtists()}) from the {@link DataManager} on demand.
1080          *
1081          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1082          */
1083         private class LazyGroup extends DefaultGroup {
1084
1085                 /** Memoizer for the artist. */
1086                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
1087
1088                         @Override
1089                         public Void call() throws Exception {
1090                                 if (!hasValue("artists")) {
1091                                         getValue("artists", Collection.class).set(getArtistsByGroup(getId()));
1092                                 }
1093                                 return null;
1094                         }
1095
1096                 });
1097
1098                 /**
1099                  * Creates a new lazy group.
1100                  *
1101                  * @param id
1102                  *            The ID of the group
1103                  */
1104                 public LazyGroup(String id) {
1105                         super(id);
1106                 }
1107
1108                 //
1109                 // DEFAULTGROUP METHODS
1110                 //
1111
1112                 /**
1113                  * {@inheritDoc}
1114                  */
1115                 @Override
1116                 public Collection<Artist> getArtists() {
1117                         artistsMemoizer.get();
1118                         return super.getArtists();
1119                 }
1120
1121         }
1122
1123         /**
1124          * {@link ObjectCreator} implementation that can create {@link Group}
1125          * objects. This specific implementation creates {@link LazyGroup}
1126          * instances.
1127          *
1128          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1129          */
1130         private class GroupCreator implements ObjectCreator<Group> {
1131
1132                 /**
1133                  * {@inheritDoc}
1134                  */
1135                 @Override
1136                 public Group createObject(ResultSet resultSet) throws SQLException {
1137                         return new LazyGroup(resultSet.getString("GROUPS.ID")).setName(resultSet.getString("GROUPS.NAME"));
1138                 }
1139
1140         }
1141
1142         /**
1143          * {@link Track} implementation that retrieves some attributes (such as
1144          * {@link #getArtists()}, and {@link #getStyles()}) from the
1145          * {@link DataManager} on demand.
1146          *
1147          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1148          */
1149         private class LazyTrack extends DefaultTrack {
1150
1151                 /** Memoizer for the artists. */
1152                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
1153
1154                         @Override
1155                         public Void call() throws Exception {
1156                                 if (!hasValue("artists")) {
1157                                         getValue("artists", List.class).set(getArtistsByTrack(getId()));
1158                                 }
1159                                 return null;
1160                         }
1161
1162                 });
1163
1164                 /** Memoizer for the styles. */
1165                 private final Memoizer<Void> stylesMemoizer = new Memoizer<Void>(new Callable<Void>() {
1166
1167                         @Override
1168                         public Void call() throws Exception {
1169                                 if (!hasValue("styles")) {
1170                                         getValue("styles", Collection.class).set(getStylesByTrack(getId()));
1171                                 }
1172                                 return null;
1173                         }
1174
1175                 });
1176
1177                 /** Memoizer for the remix artists. */
1178                 private final Memoizer<Void> remixArtistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
1179
1180                         @Override
1181                         public Void call() throws Exception {
1182                                 if (!hasValue("remixArtists")) {
1183                                         getValue("remixArtists", List.class).set(getRemixArtistsByTrack(getId()));
1184                                 }
1185                                 return null;
1186                         }
1187
1188                 });
1189
1190                 /** Memoizer for the track derivatives. */
1191                 private final Memoizer<Void> derivativesMemoizer = new Memoizer<Void>(new Callable<Void>() {
1192
1193                         @Override
1194                         public Void call() throws Exception {
1195                                 if (!hasValue("derivatives")) {
1196                                         getValue("derivatives", Collection.class).set(getTrackDerivativesByTrack(getId()));
1197                                 }
1198                                 return null;
1199                         }
1200
1201                 });
1202
1203                 /** Memoizer for the related tracks. */
1204                 private final Memoizer<Void> relatedTracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
1205
1206                         @Override
1207                         public Void call() throws Exception {
1208                                 if (!hasValue("relatedTracks")) {
1209                                         getValue("relatedTracks", Map.class).set(getRelatedTracksByTrack(getId()));
1210                                 }
1211                                 return null;
1212                         }
1213
1214                 });
1215
1216                 /**
1217                  * Creates a new track.
1218                  *
1219                  * @param id
1220                  *            The ID of the track
1221                  */
1222                 public LazyTrack(String id) {
1223                         super(id);
1224                 }
1225
1226                 //
1227                 // DEFAULTTRACK METHODS
1228                 //
1229
1230                 /**
1231                  * {@inheritDoc}
1232                  */
1233                 @Override
1234                 public List<Artist> getArtists() {
1235                         artistsMemoizer.get();
1236                         return super.getArtists();
1237                 }
1238
1239                 /**
1240                  * {@inheritDoc}
1241                  */
1242                 @Override
1243                 public Collection<Style> getStyles() {
1244                         stylesMemoizer.get();
1245                         return super.getStyles();
1246                 }
1247
1248                 /**
1249                  * {@inheritDoc}
1250                  */
1251                 @Override
1252                 public List<Artist> getRemixArtists() {
1253                         remixArtistsMemoizer.get();
1254                         return super.getRemixArtists();
1255                 }
1256
1257                 /**
1258                  * {@inheritDoc}
1259                  */
1260                 @Override
1261                 public Collection<TrackDerivative> getDerivatives() {
1262                         derivativesMemoizer.get();
1263                         return super.getDerivatives();
1264                 }
1265
1266                 /**
1267                  * {@inheritDoc}
1268                  */
1269                 @Override
1270                 public Map<Relationship, Collection<Track>> getRelatedTracks() {
1271                         relatedTracksMemoizer.get();
1272                         return super.getRelatedTracks();
1273                 }
1274
1275                 /**
1276                  * {@inheritDoc}
1277                  */
1278                 @Override
1279                 public Collection<Party> getParties() {
1280                         if (!hasValue("parties")) {
1281                                 try {
1282                                         getValue("parties", Collection.class).set(getPartiesByTrackId(getId()));
1283                                 } catch (DatabaseException de1) {
1284                                         throw new RuntimeException("Could not load Parties for Track " + getId() + ".", de1);
1285                                 }
1286                         }
1287                         return super.getParties();
1288                 }
1289
1290         }
1291
1292         /**
1293          * {@link ObjectCreator} implementation that can create {@link Track}
1294          * objects. This specific implementation creates {@link LazyTrack}
1295          * instances.
1296          *
1297          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1298          */
1299         private class TrackCreator implements ObjectCreator<Track> {
1300
1301                 /**
1302                  * {@inheritDoc}
1303                  */
1304                 @Override
1305                 public Track createObject(ResultSet resultSet) throws SQLException {
1306                         return new LazyTrack(resultSet.getString("TRACKS.ID")).setName(resultSet.getString("TRACKS.NAME")).setRemix(resultSet.getString("TRACKS.REMIX"));
1307                 }
1308
1309         }
1310
1311         /**
1312          * {@link ObjectCreator} implementation that can create
1313          * {@link TrackDerivative} objects.
1314          *
1315          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1316          */
1317         private class TrackDerivativeCreator implements ObjectCreator<TrackDerivative> {
1318
1319                 /**
1320                  * {@inheritDoc}
1321                  */
1322                 @Override
1323                 public TrackDerivative createObject(ResultSet resultSet) throws SQLException {
1324                         return new DefaultTrackDerivative(resultSet.getString("TRACK_DERIVATIVES.ID"));
1325                 }
1326
1327         }
1328
1329         /**
1330          * {@link ObjectCreator} implementation that can create {@link Style}
1331          * objects.
1332          *
1333          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1334          */
1335         private class StyleCreator implements ObjectCreator<Style> {
1336
1337                 /**
1338                  * {@inheritDoc}
1339                  */
1340                 @Override
1341                 public Style createObject(ResultSet resultSet) throws SQLException {
1342                         return new DefaultStyle(resultSet.getString("STYLES.ID")).setName(resultSet.getString("STYLES.NAME"));
1343                 }
1344
1345         }
1346
1347         /**
1348          * {@link Party} implementation that loads additional information only on
1349          * demand.
1350          *
1351          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1352          */
1353         private class LazyParty extends DefaultParty {
1354
1355                 /**
1356                  * Creates a new party.
1357                  *
1358                  * @param id
1359                  *            The ID of the party
1360                  */
1361                 public LazyParty(String id) {
1362                         super(id);
1363                 }
1364
1365                 //
1366                 // PARTY METHODS
1367                 //
1368
1369                 /**
1370                  * {@inheritDoc}
1371                  */
1372                 @Override
1373                 public Collection<Track> getReleases() {
1374                         if (!hasValue("releases")) {
1375                                 try {
1376                                         getValue("releases", Collection.class).set(getTracksByParty(getId()));
1377                                 } catch (DatabaseException de1) {
1378                                         throw new RuntimeException("Could not loaded Tracks for Party " + getId() + ".", de1);
1379                                 }
1380                         }
1381                         return super.getReleases();
1382                 }
1383
1384         }
1385
1386         /**
1387          * {@link ObjectCreator} implementation that can create {@link Party}
1388          * objects.
1389          *
1390          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1391          */
1392         private class PartyCreator implements ObjectCreator<Party> {
1393
1394                 /**
1395                  * {@inheritDoc}
1396                  */
1397                 @Override
1398                 public Party createObject(ResultSet resultSet) throws SQLException {
1399                         return new LazyParty(resultSet.getString("PARTIES.ID")).setName(resultSet.getString("PARTIES.NAME"));
1400                 }
1401
1402         }
1403
1404         /**
1405          * {@link User} implementation that retrieves some attributes (such as
1406          * {@link #getOpenIds()}) from the {@link DataManager} on demand.
1407          *
1408          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1409          */
1410         private class LazyUser extends DefaultUser {
1411
1412                 /** Memoizer for a user’s OpenIDs. */
1413                 private final Memoizer<Void> openIdMemoizer = new Memoizer<Void>(new Callable<Void>() {
1414
1415                         @Override
1416                         public Void call() throws Exception {
1417                                 if (!hasValue("openIds")) {
1418                                         getValue("openIds", Collection.class).set(getOpenIdsByUser(getId()));
1419                                 }
1420                                 return null;
1421                         }
1422                 });
1423
1424                 /**
1425                  * Creates a new user.
1426                  *
1427                  * @param id
1428                  *            The ID of the user
1429                  */
1430                 public LazyUser(String id) {
1431                         super(id);
1432                 }
1433
1434                 /**
1435                  * {@inheritDoc}
1436                  */
1437                 @Override
1438                 public Collection<String> getOpenIds() {
1439                         openIdMemoizer.get();
1440                         return super.getOpenIds();
1441                 }
1442
1443         }
1444
1445         /**
1446          * {@link ObjectCreator} implementation that can create {@link User}
1447          * objects. This specific implementation creates {@link LazyUser} instances.
1448          *
1449          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1450          */
1451         private class UserCreator implements ObjectCreator<User> {
1452
1453                 /**
1454                  * {@inheritDoc}
1455                  */
1456                 @Override
1457                 public User createObject(ResultSet resultSet) throws SQLException {
1458                         return new LazyUser(resultSet.getString("USERS.ID")).setName(resultSet.getString("USERS.NAME")).setPasswordHash(resultSet.getString("USERS.PASSWORD")).setLevel(resultSet.getInt("USERS.LEVEL"));
1459                 }
1460
1461         }
1462
1463 }