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