Add short name to groups.
[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, String shortName) 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                 query.addValueField(new ValueField("SHORT_NAME", new StringParameter(shortName)));
682                 database.insert(query);
683                 return getGroupById(id);
684         }
685
686         /**
687          * Saves the given group.
688          *
689          * @param group
690          *            The group to save
691          * @throws DatabaseException
692          *             if a database error occurs
693          */
694         public void saveGroup(Group group) throws DatabaseException {
695                 Query query = new Query(Type.UPDATE, "GROUPS");
696                 query.addValueField(new ValueField("NAME", new StringParameter(group.getName())));
697                 query.addValueField(new ValueField("SHORT_NAME", new StringParameter(group.getShortName())));
698                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("ID", new StringParameter(group.getId()))));
699                 database.update(query);
700                 /* save properties. */
701                 saveGroupProperties(group);
702         }
703
704         /**
705          * Saves the properties of the given group.
706          *
707          * @param group
708          *            The group whose properties to save
709          * @throws DatabaseException
710          *             if a database error occurs
711          */
712         public void saveGroupProperties(Group group) throws DatabaseException {
713                 saveProperties(group.getProperties(), "GROUP_PROPERTIES", "GROUP_ID", group.getId());
714         }
715
716         /**
717          * Returns all styles for the track with the given ID.
718          *
719          * @param trackId
720          *            The ID of the track
721          * @return All styles for the given track
722          * @throws DatabaseException
723          *             if a database error occurs
724          */
725         public Collection<Style> getStylesByTrack(String trackId) throws DatabaseException {
726                 Query query = new Query(Type.SELECT, "STYLES");
727                 query.addField(new Field("STYLES.*"));
728                 query.addJoin(new Join(JoinType.INNER, "TRACK_STYLES", new Field("STYLES.ID"), new Field("TRACK_STYLES.STYLE")));
729                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_STYLES.TRACK", new StringParameter(trackId))));
730                 return database.getMultiple(query, styleCreator);
731         }
732
733         /**
734          * Returns all parties.
735          *
736          * @return All parties
737          * @throws DatabaseException
738          *             if a database error occurs
739          */
740         public Collection<Party> getAllParties() throws DatabaseException {
741                 Query query = new Query(Type.SELECT, "PARTIES");
742                 query.addField(new Field("PARTIES.*"));
743                 return loadPartyProperties(database.getMultiple(query, partyCreator));
744         }
745
746         /**
747          * Returns all parties that the track with the given ID was released at.
748          *
749          * @param trackId
750          *            The ID of the track
751          * @return All parties the track was released at
752          * @throws DatabaseException
753          *             if a database error occurs
754          */
755         public Collection<Party> getPartiesByTrackId(String trackId) throws DatabaseException {
756                 Query query = new Query(Type.SELECT, "PARTIES");
757                 query.addField(new Field("PARTIES.*"));
758                 query.addJoin(new Join(JoinType.INNER, "PARTY_TRACKS", new Field("PARTY_TRACKS.PARTY"), new Field("PARTIES.ID")));
759                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("PARTY_TRACKS.TRACK", new StringParameter(trackId))));
760                 return loadPartyProperties(database.getMultiple(query, partyCreator));
761         }
762
763         /**
764          * Returns the party with the given ID.
765          *
766          * @param partyId
767          *            The ID of the party
768          * @return The party with the given ID
769          * @throws DatabaseException
770          *             if a database error occurs
771          */
772         public Party getPartyById(String partyId) throws DatabaseException {
773                 Query query = new Query(Type.SELECT, "PARTIES");
774                 query.addField(new Field("PARTIES.*"));
775                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("PARTIES.ID", new StringParameter(partyId))));
776                 return loadPartyProperties(database.getSingle(query, partyCreator));
777         }
778
779         /**
780          * Loads the properties of the given party.
781          *
782          * @param party
783          *            The party to load the properties for
784          * @return The party with its properties loaded
785          * @throws DatabaseException
786          *             if a database error occurs
787          */
788         public Party loadPartyProperties(Party party) throws DatabaseException {
789                 return loadProperties(party, "PARTY_PROPERTIES", "PARTY");
790         }
791
792         /**
793          * Loads the properties of the given parties.
794          *
795          * @param parties
796          *            The parties to load the properties for
797          * @return The parties with their properties loaded
798          * @throws DatabaseException
799          *             if a database error occurs
800          */
801         public List<Party> loadPartyProperties(List<Party> parties) throws DatabaseException {
802                 return loadProperties(parties, "PARTY_PROPERTIES", "PARTY");
803         }
804
805         /**
806          * Saves the given party.
807          *
808          * @param party
809          *            The party to save
810          * @throws DatabaseException
811          *             if a database error occurs
812          */
813         public void saveParty(Party party) throws DatabaseException {
814                 Query query = new Query(Type.UPDATE, "PARTIES");
815                 query.addValueField(new ValueField("NAME", new StringParameter(party.getName())));
816                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("ID", new StringParameter(party.getId()))));
817                 database.update(query);
818                 savePartyProperties(party);
819         }
820
821         /**
822          * Saves the properties of the given party.
823          *
824          * @param party
825          *            The party whose properties to save
826          * @throws DatabaseException
827          *             if a database error occurs
828          */
829         public void savePartyProperties(Party party) throws DatabaseException {
830                 saveProperties(party.getProperties(), "PARTY_PROPERTIES", "PARTY", party.getId());
831         }
832
833         /**
834          * Creates a new party with the given name.
835          *
836          * @param name
837          *            The name of the party
838          * @return The new party
839          * @throws DatabaseException
840          *             if a database error occurs
841          */
842         public Party createParty(String name) throws DatabaseException {
843                 Query query = new Query(Type.INSERT, "PARTIES");
844                 String id = UUID.randomUUID().toString();
845                 query.addValueField(new ValueField("ID", new StringParameter(id)));
846                 query.addValueField(new ValueField("NAME", new StringParameter(name)));
847                 database.insert(query);
848                 return getPartyById(id);
849         }
850
851         /**
852          * Returns the user with the given name.
853          *
854          * @param username
855          *            The name of the user
856          * @return The user, or {@code null} if the user does not exist
857          * @throws DatabaseException
858          *             if a database error occurs
859          */
860         public User getUserByName(String username) throws DatabaseException {
861                 Query query = new Query(Type.SELECT, "USERS");
862                 query.addField(new Field("USERS.*"));
863                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USERS.NAME", new StringParameter(username))));
864                 return database.getSingle(query, userCreator);
865         }
866
867         /**
868          * Returns the user connected with the given OpenID.
869          *
870          * @param openId
871          *            The OpenID to find the user for
872          * @return The user connected with the given OpenID, or {@code null} if
873          *         there is no such user
874          * @throws DatabaseException
875          *             if a database error occurs
876          */
877         public User getUserByOpenId(String openId) throws DatabaseException {
878                 Query query = new Query(Type.SELECT, "USERS");
879                 query.addField(new Field("USERS.*"));
880                 query.addJoin(new Join(JoinType.INNER, "USER_OPENIDS", new Field("USER_OPENIDS.USER"), new Field("USERS.ID")));
881                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.OPENID", new StringParameter(openId))));
882                 return database.getSingle(query, userCreator);
883         }
884
885         /**
886          * Returns all OpenIDs connected with the user with the given ID.
887          *
888          * @param userId
889          *            The ID of the user
890          * @return All OpenIDs connected with the given user
891          * @throws DatabaseException
892          *             if a database error occurs
893          */
894         public Collection<String> getOpenIdsByUser(String userId) throws DatabaseException {
895                 Query query = new Query(Type.SELECT, "USER_OPENIDS");
896                 query.addField(new Field("USER_OPENIDS.*"));
897                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.USER", new StringParameter(userId))));
898                 return database.getMultiple(query, new StringCreator("USER_OPENIDS.OPENID"));
899         }
900
901         //
902         // PRIVATE METHODS
903         //
904
905         /**
906          * Loads the properties for the given object.
907          *
908          * @param <T>
909          *            The type of the object
910          * @param object
911          *            The object
912          * @param table
913          *            The table to load the properties from
914          * @param type
915          *            The type of the object (“ARTIST,” “TRACK,” etc.)
916          * @return The object with its properties loaded
917          * @throws DatabaseException
918          *             if a database error occurs
919          */
920         private <T extends Base> T loadProperties(final T object, final String table, String type) throws DatabaseException {
921                 if (object == null) {
922                         return null;
923                 }
924                 Query query = new Query(Type.SELECT, table);
925                 query.addField(new Field(table + ".PROPERTY"));
926                 query.addField(new Field(table + ".VALUE"));
927                 query.addWhereClause(new ValueFieldWhereClause(new ValueField(type, new StringParameter(object.getId()))));
928                 database.process(query, new ResultProcessor() {
929
930                         @Override
931                         public void processResult(ResultSet resultSet) throws SQLException {
932                                 if (resultSet.isFirst()) {
933                                         object.getProperties().removeAll();
934                                 }
935                                 object.getProperties().set(resultSet.getString(table + ".PROPERTY"), resultSet.getString(table + ".VALUE"));
936                         }
937
938                 });
939                 return object;
940         }
941
942         /**
943          * Loads the properties for the given objects.
944          *
945          * @param <T>
946          *            The type of the object
947          * @param objects
948          *            The objects
949          * @param table
950          *            The table to load the properties from
951          * @param type
952          *            The type of the object (“ARTIST,” “TRACK,” etc.)
953          * @return The object with its properties loaded
954          * @throws DatabaseException
955          *             if a database error occurs
956          */
957         private <T extends Base> List<T> loadProperties(List<T> objects, final String table, final String type) throws DatabaseException {
958                 if (objects.isEmpty()) {
959                         return objects;
960                 }
961                 final Map<String, T> objectMap = new HashMap<String, T>();
962                 final Set<String> firstObjects = new HashSet<String>();
963                 for (T object : objects) {
964                         objectMap.put(object.getId(), object);
965                         firstObjects.add(object.getId());
966                 }
967                 Query query = new Query(Type.SELECT, table);
968                 query.addField(new Field(table + "." + type));
969                 query.addField(new Field(table + ".PROPERTY"));
970                 query.addField(new Field(table + ".VALUE"));
971                 OrWhereClause whereClause = new OrWhereClause();
972                 for (T object : objects) {
973                         whereClause.add(new ValueFieldWhereClause(new ValueField(type, new StringParameter(object.getId()))));
974                 }
975                 query.addWhereClause(whereClause);
976                 database.process(query, new ResultProcessor() {
977
978                         @Override
979                         public void processResult(ResultSet resultSet) throws SQLException {
980                                 String id = resultSet.getString(table + "." + type);
981                                 T object = objectMap.get(id);
982                                 if (firstObjects.remove(id)) {
983                                         object.getProperties().removeAll();
984                                 }
985                                 object.getProperties().set(resultSet.getString(table + ".PROPERTY"), resultSet.getString(table + ".VALUE"));
986                         }
987
988                 });
989                 return objects;
990         }
991
992         /**
993          * {@link Artist} implementation that retrieves some attributes (such as
994          * {@link #getGroups()}, and {@link #getTracks()}) from the
995          * {@link DataManager} on demand.
996          *
997          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
998          */
999         private class LazyArtist extends DefaultArtist {
1000
1001                 /** Memoizer for the tracks by this artist. */
1002                 private final Memoizer<Void> tracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
1003
1004                         @Override
1005                         public Void call() throws DatabaseException {
1006                                 if (!hasValue("tracks")) {
1007                                         getValue("tracks", Collection.class).set(getTracksByArtist(getId()));
1008                                 }
1009                                 return null;
1010                         }
1011                 });
1012
1013                 /** Memoizer for the groups of this artist. */
1014                 private final Memoizer<Void> groupsMemoizer = new Memoizer<Void>(new Callable<Void>() {
1015
1016                         @Override
1017                         public Void call() throws Exception {
1018                                 if (!hasValue("groups")) {
1019                                         getValue("groups", Collection.class).set(getGroupsByArtist(getId()));
1020                                 }
1021                                 return null;
1022                         }
1023
1024                 });
1025
1026                 /**
1027                  * Creates a new lazy artist.
1028                  *
1029                  * @param id
1030                  *            The ID of the artist
1031                  */
1032                 public LazyArtist(String id) {
1033                         super(id);
1034                 }
1035
1036                 //
1037                 // DEFAULTARTIST METHODS
1038                 //
1039
1040                 /**
1041                  * {@inheritDoc}
1042                  */
1043                 @Override
1044                 public Collection<Group> getGroups() {
1045                         groupsMemoizer.get();
1046                         return super.getGroups();
1047                 }
1048
1049                 /**
1050                  * {@inheritDoc}
1051                  */
1052                 @Override
1053                 public Collection<Track> getTracks() {
1054                         tracksMemoizer.get();
1055                         return super.getTracks();
1056                 }
1057
1058         }
1059
1060         /**
1061          * {@link ObjectCreator} implementation that can create {@link Artist}
1062          * objects. This specific class actually creates {@link LazyArtist}
1063          * instances.
1064          *
1065          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1066          */
1067         private class ArtistCreator implements ObjectCreator<Artist> {
1068
1069                 /**
1070                  * {@inheritDoc}
1071                  */
1072                 @Override
1073                 public Artist createObject(ResultSet resultSet) throws SQLException {
1074                         return new LazyArtist(resultSet.getString("ARTISTS.ID")).setName(resultSet.getString("ARTISTS.NAME"));
1075                 }
1076
1077         }
1078
1079         /**
1080          * {@link Group} implementation that retrieves some attributes (such as
1081          * {@link #getArtists()}) from the {@link DataManager} on demand.
1082          *
1083          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1084          */
1085         private class LazyGroup extends DefaultGroup {
1086
1087                 /** Memoizer for the artist. */
1088                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
1089
1090                         @Override
1091                         public Void call() throws Exception {
1092                                 if (!hasValue("artists")) {
1093                                         getValue("artists", Collection.class).set(getArtistsByGroup(getId()));
1094                                 }
1095                                 return null;
1096                         }
1097
1098                 });
1099
1100                 /**
1101                  * Creates a new lazy group.
1102                  *
1103                  * @param id
1104                  *            The ID of the group
1105                  */
1106                 public LazyGroup(String id) {
1107                         super(id);
1108                 }
1109
1110                 //
1111                 // DEFAULTGROUP METHODS
1112                 //
1113
1114                 /**
1115                  * {@inheritDoc}
1116                  */
1117                 @Override
1118                 public Collection<Artist> getArtists() {
1119                         artistsMemoizer.get();
1120                         return super.getArtists();
1121                 }
1122
1123         }
1124
1125         /**
1126          * {@link ObjectCreator} implementation that can create {@link Group}
1127          * objects. This specific implementation creates {@link LazyGroup}
1128          * instances.
1129          *
1130          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1131          */
1132         private class GroupCreator implements ObjectCreator<Group> {
1133
1134                 /**
1135                  * {@inheritDoc}
1136                  */
1137                 @Override
1138                 public Group createObject(ResultSet resultSet) throws SQLException {
1139                         return new LazyGroup(resultSet.getString("GROUPS.ID")).setName(resultSet.getString("GROUPS.NAME")).setShortName(resultSet.getString("GROUPS.SHORT_NAME"));
1140                 }
1141
1142         }
1143
1144         /**
1145          * {@link Track} implementation that retrieves some attributes (such as
1146          * {@link #getArtists()}, and {@link #getStyles()}) from the
1147          * {@link DataManager} on demand.
1148          *
1149          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1150          */
1151         private class LazyTrack extends DefaultTrack {
1152
1153                 /** Memoizer for the artists. */
1154                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
1155
1156                         @Override
1157                         public Void call() throws Exception {
1158                                 if (!hasValue("artists")) {
1159                                         getValue("artists", List.class).set(getArtistsByTrack(getId()));
1160                                 }
1161                                 return null;
1162                         }
1163
1164                 });
1165
1166                 /** Memoizer for the styles. */
1167                 private final Memoizer<Void> stylesMemoizer = new Memoizer<Void>(new Callable<Void>() {
1168
1169                         @Override
1170                         public Void call() throws Exception {
1171                                 if (!hasValue("styles")) {
1172                                         getValue("styles", Collection.class).set(getStylesByTrack(getId()));
1173                                 }
1174                                 return null;
1175                         }
1176
1177                 });
1178
1179                 /** Memoizer for the remix artists. */
1180                 private final Memoizer<Void> remixArtistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
1181
1182                         @Override
1183                         public Void call() throws Exception {
1184                                 if (!hasValue("remixArtists")) {
1185                                         getValue("remixArtists", List.class).set(getRemixArtistsByTrack(getId()));
1186                                 }
1187                                 return null;
1188                         }
1189
1190                 });
1191
1192                 /** Memoizer for the track derivatives. */
1193                 private final Memoizer<Void> derivativesMemoizer = new Memoizer<Void>(new Callable<Void>() {
1194
1195                         @Override
1196                         public Void call() throws Exception {
1197                                 if (!hasValue("derivatives")) {
1198                                         getValue("derivatives", Collection.class).set(getTrackDerivativesByTrack(getId()));
1199                                 }
1200                                 return null;
1201                         }
1202
1203                 });
1204
1205                 /** Memoizer for the related tracks. */
1206                 private final Memoizer<Void> relatedTracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
1207
1208                         @Override
1209                         public Void call() throws Exception {
1210                                 if (!hasValue("relatedTracks")) {
1211                                         getValue("relatedTracks", Map.class).set(getRelatedTracksByTrack(getId()));
1212                                 }
1213                                 return null;
1214                         }
1215
1216                 });
1217
1218                 /**
1219                  * Creates a new track.
1220                  *
1221                  * @param id
1222                  *            The ID of the track
1223                  */
1224                 public LazyTrack(String id) {
1225                         super(id);
1226                 }
1227
1228                 //
1229                 // DEFAULTTRACK METHODS
1230                 //
1231
1232                 /**
1233                  * {@inheritDoc}
1234                  */
1235                 @Override
1236                 public List<Artist> getArtists() {
1237                         artistsMemoizer.get();
1238                         return super.getArtists();
1239                 }
1240
1241                 /**
1242                  * {@inheritDoc}
1243                  */
1244                 @Override
1245                 public Collection<Style> getStyles() {
1246                         stylesMemoizer.get();
1247                         return super.getStyles();
1248                 }
1249
1250                 /**
1251                  * {@inheritDoc}
1252                  */
1253                 @Override
1254                 public List<Artist> getRemixArtists() {
1255                         remixArtistsMemoizer.get();
1256                         return super.getRemixArtists();
1257                 }
1258
1259                 /**
1260                  * {@inheritDoc}
1261                  */
1262                 @Override
1263                 public Collection<TrackDerivative> getDerivatives() {
1264                         derivativesMemoizer.get();
1265                         return super.getDerivatives();
1266                 }
1267
1268                 /**
1269                  * {@inheritDoc}
1270                  */
1271                 @Override
1272                 public Map<Relationship, Collection<Track>> getRelatedTracks() {
1273                         relatedTracksMemoizer.get();
1274                         return super.getRelatedTracks();
1275                 }
1276
1277                 /**
1278                  * {@inheritDoc}
1279                  */
1280                 @Override
1281                 public Collection<Party> getParties() {
1282                         if (!hasValue("parties")) {
1283                                 try {
1284                                         getValue("parties", Collection.class).set(getPartiesByTrackId(getId()));
1285                                 } catch (DatabaseException de1) {
1286                                         throw new RuntimeException("Could not load Parties for Track " + getId() + ".", de1);
1287                                 }
1288                         }
1289                         return super.getParties();
1290                 }
1291
1292         }
1293
1294         /**
1295          * {@link ObjectCreator} implementation that can create {@link Track}
1296          * objects. This specific implementation creates {@link LazyTrack}
1297          * instances.
1298          *
1299          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1300          */
1301         private class TrackCreator implements ObjectCreator<Track> {
1302
1303                 /**
1304                  * {@inheritDoc}
1305                  */
1306                 @Override
1307                 public Track createObject(ResultSet resultSet) throws SQLException {
1308                         return new LazyTrack(resultSet.getString("TRACKS.ID")).setName(resultSet.getString("TRACKS.NAME")).setRemix(resultSet.getString("TRACKS.REMIX"));
1309                 }
1310
1311         }
1312
1313         /**
1314          * {@link ObjectCreator} implementation that can create
1315          * {@link TrackDerivative} objects.
1316          *
1317          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1318          */
1319         private class TrackDerivativeCreator implements ObjectCreator<TrackDerivative> {
1320
1321                 /**
1322                  * {@inheritDoc}
1323                  */
1324                 @Override
1325                 public TrackDerivative createObject(ResultSet resultSet) throws SQLException {
1326                         return new DefaultTrackDerivative(resultSet.getString("TRACK_DERIVATIVES.ID"));
1327                 }
1328
1329         }
1330
1331         /**
1332          * {@link ObjectCreator} implementation that can create {@link Style}
1333          * objects.
1334          *
1335          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1336          */
1337         private class StyleCreator implements ObjectCreator<Style> {
1338
1339                 /**
1340                  * {@inheritDoc}
1341                  */
1342                 @Override
1343                 public Style createObject(ResultSet resultSet) throws SQLException {
1344                         return new DefaultStyle(resultSet.getString("STYLES.ID")).setName(resultSet.getString("STYLES.NAME"));
1345                 }
1346
1347         }
1348
1349         /**
1350          * {@link Party} implementation that loads additional information only on
1351          * demand.
1352          *
1353          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1354          */
1355         private class LazyParty extends DefaultParty {
1356
1357                 /**
1358                  * Creates a new party.
1359                  *
1360                  * @param id
1361                  *            The ID of the party
1362                  */
1363                 public LazyParty(String id) {
1364                         super(id);
1365                 }
1366
1367                 //
1368                 // PARTY METHODS
1369                 //
1370
1371                 /**
1372                  * {@inheritDoc}
1373                  */
1374                 @Override
1375                 public Collection<Track> getReleases() {
1376                         if (!hasValue("releases")) {
1377                                 try {
1378                                         getValue("releases", Collection.class).set(getTracksByParty(getId()));
1379                                 } catch (DatabaseException de1) {
1380                                         throw new RuntimeException("Could not loaded Tracks for Party " + getId() + ".", de1);
1381                                 }
1382                         }
1383                         return super.getReleases();
1384                 }
1385
1386         }
1387
1388         /**
1389          * {@link ObjectCreator} implementation that can create {@link Party}
1390          * objects.
1391          *
1392          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1393          */
1394         private class PartyCreator implements ObjectCreator<Party> {
1395
1396                 /**
1397                  * {@inheritDoc}
1398                  */
1399                 @Override
1400                 public Party createObject(ResultSet resultSet) throws SQLException {
1401                         return new LazyParty(resultSet.getString("PARTIES.ID")).setName(resultSet.getString("PARTIES.NAME"));
1402                 }
1403
1404         }
1405
1406         /**
1407          * {@link User} implementation that retrieves some attributes (such as
1408          * {@link #getOpenIds()}) from the {@link DataManager} on demand.
1409          *
1410          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1411          */
1412         private class LazyUser extends DefaultUser {
1413
1414                 /** Memoizer for a user’s OpenIDs. */
1415                 private final Memoizer<Void> openIdMemoizer = new Memoizer<Void>(new Callable<Void>() {
1416
1417                         @Override
1418                         public Void call() throws Exception {
1419                                 if (!hasValue("openIds")) {
1420                                         getValue("openIds", Collection.class).set(getOpenIdsByUser(getId()));
1421                                 }
1422                                 return null;
1423                         }
1424                 });
1425
1426                 /**
1427                  * Creates a new user.
1428                  *
1429                  * @param id
1430                  *            The ID of the user
1431                  */
1432                 public LazyUser(String id) {
1433                         super(id);
1434                 }
1435
1436                 /**
1437                  * {@inheritDoc}
1438                  */
1439                 @Override
1440                 public Collection<String> getOpenIds() {
1441                         openIdMemoizer.get();
1442                         return super.getOpenIds();
1443                 }
1444
1445         }
1446
1447         /**
1448          * {@link ObjectCreator} implementation that can create {@link User}
1449          * objects. This specific implementation creates {@link LazyUser} instances.
1450          *
1451          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1452          */
1453         private class UserCreator implements ObjectCreator<User> {
1454
1455                 /**
1456                  * {@inheritDoc}
1457                  */
1458                 @Override
1459                 public User createObject(ResultSet resultSet) throws SQLException {
1460                         return new LazyUser(resultSet.getString("USERS.ID")).setName(resultSet.getString("USERS.NAME")).setPasswordHash(resultSet.getString("USERS.PASSWORD")).setLevel(resultSet.getInt("USERS.LEVEL"));
1461                 }
1462
1463         }
1464
1465 }