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