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