Add method to create a new derivative for a track.
[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.StringParameter;
42 import net.pterodactylus.util.database.Query;
43 import net.pterodactylus.util.database.Query.Type;
44 import net.pterodactylus.util.database.ResultProcessor;
45 import net.pterodactylus.util.database.ValueField;
46 import net.pterodactylus.util.database.ValueFieldWhereClause;
47
48 /**
49  * Interface between the database and the application.
50  *
51  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52  */
53 public class DataManager {
54
55         /** The artist object creator. */
56         @SuppressWarnings("synthetic-access")
57         private final ObjectCreator<Artist> artistCreator = new ArtistCreator();
58
59         /** The group object creator. */
60         @SuppressWarnings("synthetic-access")
61         private final ObjectCreator<Group> groupCreator = new GroupCreator();
62
63         /** The track object creator. */
64         @SuppressWarnings("synthetic-access")
65         private final ObjectCreator<Track> trackCreator = new TrackCreator();
66
67         /** The track object creator. */
68         @SuppressWarnings("synthetic-access")
69         private final ObjectCreator<TrackDerivative> trackDerivativeCreator = new TrackDerivativeCreator();
70
71         /** The style object creator. */
72         @SuppressWarnings("synthetic-access")
73         private final ObjectCreator<Style> styleCreator = new StyleCreator();
74
75         /** The {@link User} object creator. */
76         @SuppressWarnings("synthetic-access")
77         private final ObjectCreator<User> userCreator = new UserCreator();
78
79         /** The database. */
80         private final Database database;
81
82         /**
83          * Creates a new data manager.
84          *
85          * @param database
86          *            The database to operate on
87          */
88         public DataManager(Database database) {
89                 this.database = database;
90         }
91
92         /**
93          * Returns all artists.
94          *
95          * @return All artists
96          * @throws DatabaseException
97          *             if a database error occurs
98          */
99         public Collection<Artist> getAllArtists() throws DatabaseException {
100                 Query query = new Query(Type.SELECT, "ARTISTS");
101                 query.addField(new Field("ARTISTS.*"));
102                 return loadArtistProperties(database.getMultiple(query, artistCreator));
103         }
104
105         /**
106          * Returns the artist with the given ID.
107          *
108          * @param id
109          *            The ID of the artist
110          * @return The artist with the given ID, or {@code null} if there is no
111          *         artist with the given ID
112          * @throws DatabaseException
113          *             if a database error occurs
114          */
115         public Artist getArtistById(String id) throws DatabaseException {
116                 Query query = new Query(Type.SELECT, "ARTISTS");
117                 query.addField(new Field("ARTISTS.*"));
118                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("ARTISTS.ID", new StringParameter(id))));
119                 return loadArtistProperties(database.getSingle(query, artistCreator));
120         }
121
122         /**
123          * Returns all artists that belong to the group with the given ID.
124          *
125          * @param groupId
126          *            The ID of the group
127          * @return All artists belonging to the given group
128          * @throws DatabaseException
129          *             if a database error occurs
130          */
131         public Collection<Artist> getArtistsByGroup(String groupId) throws DatabaseException {
132                 Query query = new Query(Type.SELECT, "ARTISTS");
133                 query.addField(new Field("ARTISTS.*"));
134                 query.addJoin(new Join(JoinType.INNER, "GROUP_ARTISTS", new Field("ARTISTS.ID"), new Field("GROUP_ARTISTS.ARTIST")));
135                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUP_ARTISTS.GROUP_", new StringParameter(groupId))));
136                 return loadArtistProperties(database.getMultiple(query, artistCreator));
137         }
138
139         /**
140          * Returns all artists involved in the track with the given ID.
141          *
142          * @param trackId
143          *            The ID of the track
144          * @return All artists involved in the track, in preferred order
145          * @throws DatabaseException
146          *             if a database error occurs
147          */
148         public List<Artist> getArtistsByTrack(String trackId) throws DatabaseException {
149                 Query query = new Query(Type.SELECT, "ARTISTS");
150                 query.addField(new Field("ARTISTS.*"));
151                 query.addJoin(new Join(JoinType.INNER, "TRACK_ARTISTS", new Field("TRACK_ARTISTS.ARTIST"), new Field("ARTISTS.ID")));
152                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_ARTISTS.TRACK", new StringParameter(trackId))));
153                 query.addOrderField(new OrderField(new Field("TRACK_ARTISTS.DISPLAY_ORDER")));
154                 return loadArtistProperties(database.getMultiple(query, artistCreator));
155         }
156
157         /**
158          * Creates a new artist with the given name.
159          *
160          * @param name
161          *            The name of the artist
162          * @return The created artist
163          * @throws DatabaseException
164          *             if a database error occurs
165          */
166         public Artist createArtist(String name) throws DatabaseException {
167                 Query query = new Query(Type.INSERT, "ARTISTS");
168                 String id = UUID.randomUUID().toString();
169                 query.addValueField(new ValueField("ID", new StringParameter(id)));
170                 query.addValueField(new ValueField("NAME", new StringParameter(name)));
171                 database.insert(query);
172                 return loadArtistProperties(getArtistById(id));
173         }
174
175         /**
176          * Saves the given artist.
177          *
178          * @param artist
179          *            The artist to save
180          * @throws DatabaseException
181          *             if a database error occurs
182          */
183         public void saveArtist(Artist artist) throws DatabaseException {
184                 Query query = new Query(Type.UPDATE, "ARTISTS");
185                 query.addValueField(new ValueField("NAME", new StringParameter(artist.getName())));
186                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("ID", new StringParameter(artist.getId()))));
187                 database.update(query);
188                 saveArtistProperties(artist);
189         }
190
191         /**
192          * Saves the properties of the given artist.
193          *
194          * @param artist
195          *            The artist whose properties to save
196          * @throws DatabaseException
197          *             if a database error occurs
198          */
199         public void saveArtistProperties(Artist artist) throws DatabaseException {
200                 saveProperties(artist.getProperties(), "ARTIST_PROPERTIES", "ARTIST", artist.getId());
201         }
202
203         /**
204          * Saves the given properties to the given table for the given principal.
205          *
206          * @param properties
207          *            The properties to save
208          * @param table
209          *            The table in which to save the properties
210          * @param type
211          *            The type of the principal (e. g. “ARTIST” or “TRACK”)
212          * @param id
213          *            The ID of the principial
214          * @throws DatabaseException
215          *             if a database error occurs
216          */
217         public void saveProperties(Properties properties, String table, String type, String id) throws DatabaseException {
218                 if (!properties.isDirty()) {
219                         return;
220                 }
221                 Query query = new Query(Type.DELETE, table);
222                 query.addWhereClause(new ValueFieldWhereClause(new ValueField(type, new StringParameter(id))));
223                 database.update(query);
224                 for (Entry<String, String> property : properties) {
225                         Query insertQuery = new Query(Type.INSERT, table);
226                         insertQuery.addValueField(new ValueField(type, new StringParameter(id)));
227                         insertQuery.addValueField(new ValueField("PROPERTY", new StringParameter(property.getKey())));
228                         insertQuery.addValueField(new ValueField("VALUE", new StringParameter(property.getValue())));
229                         database.insert(insertQuery);
230                 }
231                 properties.resetDirty();
232         }
233
234         /**
235          * Loads the properties for an artist.
236          *
237          * @param artist
238          *            The artist to load the properties for
239          * @return The artist
240          * @throws DatabaseException
241          *             if a database error occurs
242          */
243         public Artist loadArtistProperties(final Artist artist) throws DatabaseException {
244                 return loadProperties(artist, "ARTIST_PROPERTIES", "ARTIST");
245         }
246
247         /**
248          * Loads the properties of all given artists.
249          *
250          * @param artists
251          *            The artists to load the properties for
252          * @return The list of artists
253          * @throws DatabaseException
254          *             if a database error occurs
255          */
256         public List<Artist> loadArtistProperties(List<Artist> artists) throws DatabaseException {
257                 for (Artist artist : artists) {
258                         loadArtistProperties(artist);
259                 }
260                 return artists;
261         }
262
263         /**
264          * Returns all remix artists involved in the track with the given ID.
265          *
266          * @param trackId
267          *            The ID of the track
268          * @return All remix artists involved in the track, in preferred order
269          * @throws DatabaseException
270          *             if a database error occurs
271          */
272         public List<Artist> getRemixArtistsByTrack(String trackId) throws DatabaseException {
273                 Query query = new Query(Type.SELECT, "ARTISTS");
274                 query.addField(new Field("ARTISTS.*"));
275                 query.addJoin(new Join(JoinType.INNER, "TRACK_REMIX_ARTISTS", new Field("TRACK_REMIX_ARTISTS.ARTIST"), new Field("ARTISTS.ID")));
276                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_REMIX_ARTISTS.TRACK", new StringParameter(trackId))));
277                 query.addOrderField(new OrderField(new Field("TRACK_REMIX_ARTISTS.DISPLAY_ORDER")));
278                 return database.getMultiple(query, artistCreator);
279         }
280
281         /**
282          * Returns all related tracks for the track with the given ID.
283          *
284          * @param trackId
285          *            The ID of the tracks
286          * @return A mapping from relationship to all tracks that match the relation
287          * @throws DatabaseException
288          *             if a database error occurs
289          */
290         public Map<Relationship, Collection<Track>> getRelatedTracksByTrack(String trackId) throws DatabaseException {
291                 Query query = new Query(Type.SELECT, "TRACKS");
292                 query.addField(new Field("TRACKS.*"));
293                 query.addField(new Field("TRACK_RELATIONS.*"));
294                 query.addJoin(new Join(JoinType.INNER, "TRACK_RELATIONS", new Field("TRACK_RELATIONS.TRACK"), new Field("TRACK_RELATIONS.RELATED_TRACK")));
295                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_RELATIONS.TRACK", new StringParameter(trackId))));
296                 final Map<Relationship, Collection<Track>> relatedTracks = new EnumMap<Relationship, Collection<Track>>(Relationship.class);
297                 database.process(query, new ResultProcessor() {
298
299                         @Override
300                         @SuppressWarnings("synthetic-access")
301                         public void processResult(ResultSet resultSet) throws SQLException {
302                                 Track track = trackCreator.createObject(resultSet);
303                                 Relationship relationship = Relationship.valueOf(resultSet.getString("TRACK_RELATIONS.RELATIONSHIP"));
304                                 if (!relatedTracks.containsKey(relationship)) {
305                                         relatedTracks.put(relationship, new HashSet<Track>());
306                                 }
307                                 relatedTracks.get(relationship).add(track);
308                         }
309                 });
310                 return relatedTracks;
311         }
312
313         /**
314          * Returns the track with the given ID.
315          *
316          * @param id
317          *            The ID of the track
318          * @return The track with the given ID, or {@code null} if there is no such
319          *         track
320          * @throws DatabaseException
321          *             if a database error occurs
322          */
323         public Track getTrackById(String id) throws DatabaseException {
324                 Query query = new Query(Type.SELECT, "TRACKS");
325                 query.addField(new Field("TRACKS.*"));
326                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACKS.ID", new StringParameter(id))));
327                 return database.getSingle(query, trackCreator);
328         }
329
330         /**
331          * Returns all tracks by the artist with the given ID.
332          *
333          * @param artistId
334          *            The ID of the artist
335          * @return All tracks by the given artist
336          * @throws DatabaseException
337          *             if a database error occurs
338          */
339         public Collection<Track> getTracksByArtist(String artistId) throws DatabaseException {
340                 Query query = new Query(Type.SELECT, "TRACKS");
341                 query.addField(new Field("TRACKS.*"));
342                 query.addJoin(new Join(JoinType.INNER, "TRACK_ARTISTS", new Field("TRACKS.ID"), new Field("TRACK_ARTISTS.TRACK")));
343                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_ARTISTS.ARTIST", new StringParameter(artistId))));
344                 return database.getMultiple(query, trackCreator);
345         }
346
347         /**
348          * Returns the derivative with the given ID.
349          *
350          * @param id
351          *            The ID of the derivatives to load
352          * @return The derivative with the given ID
353          * @throws DatabaseException
354          *             if a database error occurs
355          */
356         public TrackDerivative getTrackDerivativeById(String id) throws DatabaseException {
357                 Query query = new Query(Type.SELECT, "TRACK_DERIVATIVES");
358                 query.addField(new Field("TRACK_DERIVATIVES.*"));
359                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_DERIVATIVES.ID", new StringParameter(id))));
360                 return loadTrackDerivativeProperties(database.getSingle(query, trackDerivativeCreator));
361         }
362
363         /**
364          * Returns the derivatives for the given track.
365          *
366          * @param track
367          *            The track to get the derivatives for
368          * @return The derivatives for the given track
369          * @throws DatabaseException
370          *             if a database error occurs
371          */
372         public Collection<TrackDerivative> getTrackDerivativesByTrack(Track track) throws DatabaseException {
373                 Query query = new Query(Type.SELECT, "TRACK_DERIVATIVES");
374                 query.addField(new Field("TRACK_DERIVATIVES.*"));
375                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_DERIVATIVES.TRACK", new StringParameter(track.getId()))));
376                 return loadTrackDerivativeProperties(database.getMultiple(query, trackDerivativeCreator));
377         }
378
379         /**
380          * Creates a new derivative for the given track.
381          *
382          * @param track
383          *            The track to create the derivative for
384          * @return The created derivative
385          * @throws DatabaseException
386          *             if a database error occurs
387          */
388         public TrackDerivative createTrackDerivative(Track track) throws DatabaseException {
389                 Query query = new Query(Type.INSERT, "TRACK_DERIVATIVES");
390                 String id = UUID.randomUUID().toString();
391                 query.addValueField(new ValueField("TRACK_DERIVATIVES.ID", new StringParameter(id)));
392                 query.addValueField(new ValueField("TRACK_DERIVATIVES.TRACK", new StringParameter(track.getId())));
393                 database.insert(query);
394                 return getTrackDerivativeById(id);
395         }
396
397         /**
398          * Loads the properties for the given track derivative.
399          *
400          * @param trackDerivative
401          *            The track derivative to load the properties for
402          * @return The track derivative with its properties loaded
403          * @throws DatabaseException
404          *             if a database error occurs
405          */
406         public TrackDerivative loadTrackDerivativeProperties(TrackDerivative trackDerivative) throws DatabaseException {
407                 return loadProperties(trackDerivative, "TRACK_DERIVATIVE_PROPERTIES", "TRACK_DERIVATIVE");
408         }
409
410         /**
411          * Loads the properties for the given track derivatives.
412          *
413          * @param trackDerivatives
414          *            The track derivatives to load the properties for
415          * @return The track derivatives with their properties loaded
416          * @throws DatabaseException
417          *             if a database error occurs
418          */
419         public List<TrackDerivative> loadTrackDerivativeProperties(List<TrackDerivative> trackDerivatives) throws DatabaseException {
420                 for (TrackDerivative trackDerivative : trackDerivatives) {
421                         loadTrackDerivativeProperties(trackDerivative);
422                 }
423                 return trackDerivatives;
424         }
425
426         /**
427          * Returns all groups the artist with the given ID belongs to.
428          *
429          * @param artistId
430          *            The ID of the artist
431          * @return All groups the artist belongs to
432          * @throws DatabaseException
433          *             if a database error occurs
434          */
435         public Collection<Group> getGroupsByArtist(String artistId) throws DatabaseException {
436                 Query query = new Query(Type.SELECT, "GROUPS");
437                 query.addField(new Field("GROUPS.*"));
438                 query.addJoin(new Join(JoinType.INNER, "GROUP_ARTISTS", new Field("GROUPS.ID"), new Field("GROUP_ARTISTS.GROUP_")));
439                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUP_ARTISTS.ARTIST", new StringParameter(artistId))));
440                 return database.getMultiple(query, groupCreator);
441         }
442
443         /**
444          * Returns all styles for the track with the given ID.
445          *
446          * @param trackId
447          *            The ID of the track
448          * @return All styles for the given track
449          * @throws DatabaseException
450          *             if a database error occurs
451          */
452         public Collection<Style> getStylesByTrack(String trackId) throws DatabaseException {
453                 Query query = new Query(Type.SELECT, "STYLES");
454                 query.addField(new Field("STYLES.*"));
455                 query.addJoin(new Join(JoinType.INNER, "TRACK_STYLES", new Field("STYLES.ID"), new Field("TRACK_STYLES.STYLE")));
456                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_STYLES.TRACK", new StringParameter(trackId))));
457                 return database.getMultiple(query, styleCreator);
458         }
459
460         /**
461          * Returns the user with the given name.
462          *
463          * @param username
464          *            The name of the user
465          * @return The user, or {@code null} if the user does not exist
466          * @throws DatabaseException
467          *             if a database error occurs
468          */
469         public User getUserByName(String username) throws DatabaseException {
470                 Query query = new Query(Type.SELECT, "USERS");
471                 query.addField(new Field("USERS.*"));
472                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USERS.NAME", new StringParameter(username))));
473                 return database.getSingle(query, userCreator);
474         }
475
476         /**
477          * Returns the user connected with the given OpenID.
478          *
479          * @param openId
480          *            The OpenID to find the user for
481          * @return The user connected with the given OpenID, or {@code null} if
482          *         there is no such user
483          * @throws DatabaseException
484          *             if a database error occurs
485          */
486         public User getUserByOpenId(String openId) throws DatabaseException {
487                 Query query = new Query(Type.SELECT, "USERS");
488                 query.addField(new Field("USERS.*"));
489                 query.addJoin(new Join(JoinType.INNER, "USER_OPENIDS", new Field("USER_OPENIDS.USER"), new Field("USERS.ID")));
490                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.OPENID", new StringParameter(openId))));
491                 return database.getSingle(query, userCreator);
492         }
493
494         /**
495          * Returns all OpenIDs connected with the user with the given ID.
496          *
497          * @param userId
498          *            The ID of the user
499          * @return All OpenIDs connected with the given user
500          * @throws DatabaseException
501          *             if a database error occurs
502          */
503         public Collection<String> getOpenIdsByUser(String userId) throws DatabaseException {
504                 Query query = new Query(Type.SELECT, "USER_OPENIDS");
505                 query.addField(new Field("USER_OPENIDS.*"));
506                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.USER", new StringParameter(userId))));
507                 return database.getMultiple(query, new StringCreator("USER_OPENIDS.OPENID"));
508         }
509
510         //
511         // PRIVATE METHODS
512         //
513
514         /**
515          * Loads the properties for the given object.
516          *
517          * @param <T>
518          *            The type of the object
519          * @param object
520          *            The object
521          * @param table
522          *            The table to load the properties from
523          * @param type
524          *            The type of the object (“ARTIST,” “TRACK,” etc.)
525          * @return The object with its properties loaded
526          * @throws DatabaseException
527          *             if a database error occurs
528          */
529         private <T extends Base> T loadProperties(final T object, final String table, String type) throws DatabaseException {
530                 Query query = new Query(Type.SELECT, table);
531                 query.addField(new Field(table + ".PROPERTY"));
532                 query.addField(new Field(table + ".VALUE"));
533                 query.addWhereClause(new ValueFieldWhereClause(new ValueField(type, new StringParameter(object.getId()))));
534                 database.process(query, new ResultProcessor() {
535
536                         @Override
537                         public void processResult(ResultSet resultSet) throws SQLException {
538                                 if (resultSet.isFirst()) {
539                                         object.getProperties().removeAll();
540                                 }
541                                 object.getProperties().set(resultSet.getString(table + ".PROPERTY"), resultSet.getString(table + ".VALUE"));
542                         }
543
544                 });
545                 return object;
546         }
547
548         /**
549          * {@link Artist} implementation that retrieves some attributes (such as
550          * {@link #getGroups()}, and {@link #getTracks()}) from the
551          * {@link DataManager} on demand.
552          *
553          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
554          */
555         private class LazyArtist extends DefaultArtist {
556
557                 /** Memoizer for the tracks by this artist. */
558                 private final Memoizer<Void> tracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
559                         @Override
560                         public Void call() throws DatabaseException {
561                                 if (!hasValue("tracks")) {
562                                         getValue("tracks", Collection.class).set(getTracksByArtist(getId()));
563                                 }
564                                 return null;
565                         }
566                 });
567
568                 /** Memoizer for the groups of this artist. */
569                 private final Memoizer<Void> groupsMemoizer = new Memoizer<Void>(new Callable<Void>() {
570
571                         @Override
572                         public Void call() throws Exception {
573                                 if (!hasValue("groups")) {
574                                         getValue("groups", Collection.class).set(getGroupsByArtist(getId()));
575                                 }
576                                 return null;
577                         }
578
579                 });
580
581                 /**
582                  * Creates a new lazy artist.
583                  *
584                  * @param id
585                  *            The ID of the artist
586                  */
587                 public LazyArtist(String id) {
588                         super(id);
589                 }
590
591                 //
592                 // DEFAULTARTIST METHODS
593                 //
594
595                 /**
596                  * {@inheritDoc}
597                  */
598                 @Override
599                 public Collection<Group> getGroups() {
600                         groupsMemoizer.get();
601                         return super.getGroups();
602                 }
603
604                 /**
605                  * {@inheritDoc}
606                  */
607                 @Override
608                 public Collection<Track> getTracks() {
609                         tracksMemoizer.get();
610                         return super.getTracks();
611                 }
612
613         }
614
615         /**
616          * {@link ObjectCreator} implementation that can create {@link Artist}
617          * objects. This specific class actually creates {@link LazyArtist}
618          * instances.
619          *
620          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
621          */
622         private class ArtistCreator implements ObjectCreator<Artist> {
623
624                 /**
625                  * {@inheritDoc}
626                  */
627                 @Override
628                 public Artist createObject(ResultSet resultSet) throws SQLException {
629                         return new LazyArtist(resultSet.getString("ARTISTS.ID")).setName(resultSet.getString("ARTISTS.NAME"));
630                 }
631
632         }
633
634         /**
635          * {@link Group} implementation that retrieves some attributes (such as
636          * {@link #getArtists()}) from the {@link DataManager} on demand.
637          *
638          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
639          */
640         private class LazyGroup extends DefaultGroup {
641
642                 /** Memoizer for the artist. */
643                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
644
645                         @Override
646                         public Void call() throws Exception {
647                                 if (!hasValue("artists")) {
648                                         getValue("artists", Collection.class).set(getArtistsByGroup(getId()));
649                                 }
650                                 return null;
651                         }
652
653                 });
654
655                 /**
656                  * Creates a new lazy group.
657                  *
658                  * @param id
659                  *            The ID of the group
660                  */
661                 public LazyGroup(String id) {
662                         super(id);
663                 }
664
665                 //
666                 // DEFAULTGROUP METHODS
667                 //
668
669                 /**
670                  * {@inheritDoc}
671                  */
672                 @Override
673                 public Collection<Artist> getArtists() {
674                         artistsMemoizer.get();
675                         return super.getArtists();
676                 }
677
678         }
679
680         /**
681          * {@link ObjectCreator} implementation that can create {@link Group}
682          * objects. This specific implementation creates {@link LazyGroup}
683          * instances.
684          *
685          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
686          */
687         private class GroupCreator implements ObjectCreator<Group> {
688
689                 /**
690                  * {@inheritDoc}
691                  */
692                 @Override
693                 public Group createObject(ResultSet resultSet) throws SQLException {
694                         return new LazyGroup(resultSet.getString("GROUPS.ID")).setName(resultSet.getString("GROUPS.NAME")).setUrl(resultSet.getString("GROUPS.URL"));
695                 }
696
697         }
698
699         /**
700          * {@link Track} implementation that retrieves some attributes (such as
701          * {@link #getArtists()}, and {@link #getStyles()}) from the
702          * {@link DataManager} on demand.
703          *
704          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
705          */
706         private class LazyTrack extends DefaultTrack {
707
708                 /** Memoizer for the artists. */
709                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
710
711                         @Override
712                         public Void call() throws Exception {
713                                 if (!hasValue("artists")) {
714                                         getValue("artists", List.class).set(getArtistsByTrack(getId()));
715                                 }
716                                 return null;
717                         }
718
719                 });
720
721                 /** Memoizer for the styles. */
722                 private final Memoizer<Void> stylesMemoizer = new Memoizer<Void>(new Callable<Void>() {
723
724                         @Override
725                         public Void call() throws Exception {
726                                 if (!hasValue("styles")) {
727                                         getValue("styles", Collection.class).set(getStylesByTrack(getId()));
728                                 }
729                                 return null;
730                         }
731
732                 });
733
734                 /** Memoizer for the remix artists. */
735                 private final Memoizer<Void> remixArtistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
736
737                         @Override
738                         public Void call() throws Exception {
739                                 if (!hasValue("remixArtists")) {
740                                         getValue("remixArtists", List.class).set(getRemixArtistsByTrack(getId()));
741                                 }
742                                 return null;
743                         }
744
745                 });
746
747                 /** Memoizer for the track derivatives. */
748                 private final Memoizer<Void> derivativesMemoizer = new Memoizer<Void>(new Callable<Void>() {
749
750                         @Override
751                         public Void call() throws Exception {
752                                 if (!hasValue("derivatives")) {
753                                         getValue("derivatives", Collection.class).set(getTrackDerivativesByTrack(LazyTrack.this));
754                                 }
755                                 return null;
756                         }
757
758                 });
759
760                 /** Memoizer for the related tracks. */
761                 private final Memoizer<Void> relatedTracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
762
763                         @Override
764                         public Void call() throws Exception {
765                                 if (!hasValue("relatedTracks")) {
766                                         getValue("relatedTracks", Map.class).set(getRelatedTracksByTrack(getId()));
767                                 }
768                                 return null;
769                         }
770                 });
771
772                 /**
773                  * Creates a new track.
774                  *
775                  * @param id
776                  *            The ID of the track
777                  */
778                 public LazyTrack(String id) {
779                         super(id);
780                 }
781
782                 //
783                 // DEFAULTTRACK METHODS
784                 //
785
786                 /**
787                  * {@inheritDoc}
788                  */
789                 @Override
790                 public List<Artist> getArtists() {
791                         artistsMemoizer.get();
792                         return super.getArtists();
793                 }
794
795                 /**
796                  * {@inheritDoc}
797                  */
798                 @Override
799                 public Collection<Style> getStyles() {
800                         stylesMemoizer.get();
801                         return super.getStyles();
802                 }
803
804                 /**
805                  * {@inheritDoc}
806                  */
807                 @Override
808                 public List<Artist> getRemixArtists() {
809                         remixArtistsMemoizer.get();
810                         return super.getRemixArtists();
811                 }
812
813                 /**
814                  * {@inheritDoc}
815                  */
816                 @Override
817                 public Collection<TrackDerivative> getDerivatives() {
818                         derivativesMemoizer.get();
819                         return super.getDerivatives();
820                 }
821
822                 /**
823                  * {@inheritDoc}
824                  */
825                 @Override
826                 public Map<Relationship, Collection<Track>> getRelatedTracks() {
827                         relatedTracksMemoizer.get();
828                         return super.getRelatedTracks();
829                 }
830
831         }
832
833         /**
834          * {@link ObjectCreator} implementation that can create {@link Track}
835          * objects. This specific implementation creates {@link LazyTrack}
836          * instances.
837          *
838          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
839          */
840         private class TrackCreator implements ObjectCreator<Track> {
841
842                 /**
843                  * {@inheritDoc}
844                  */
845                 @Override
846                 public Track createObject(ResultSet resultSet) throws SQLException {
847                         return new LazyTrack(resultSet.getString("TRACKS.ID")).setName(resultSet.getString("TRACKS.NAME")).setRemix(resultSet.getString("TRACKS.REMIX"));
848                 }
849
850         }
851
852         /**
853          * {@link ObjectCreator} implementation that can create
854          * {@link TrackDerivative} objects.
855          *
856          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
857          */
858         private class TrackDerivativeCreator implements ObjectCreator<TrackDerivative> {
859
860                 /**
861                  * {@inheritDoc}
862                  */
863                 @Override
864                 public TrackDerivative createObject(ResultSet resultSet) throws SQLException {
865                         return new DefaultTrackDerivative(resultSet.getString("TRACK_DERIVATIVES.ID"));
866                 }
867
868         }
869
870         /**
871          * {@link ObjectCreator} implementation that can create {@link Style}
872          * objects.
873          *
874          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
875          */
876         private class StyleCreator implements ObjectCreator<Style> {
877
878                 /**
879                  * {@inheritDoc}
880                  */
881                 @Override
882                 public Style createObject(ResultSet resultSet) throws SQLException {
883                         return new DefaultStyle(resultSet.getString("STYLES.ID")).setName(resultSet.getString("STYLES.NAME"));
884                 }
885
886         }
887
888         /**
889          * {@link User} implementation that retrieves some attributes (such as
890          * {@link #getOpenIds()}) from the {@link DataManager} on demand.
891          *
892          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
893          */
894         private class LazyUser extends DefaultUser {
895
896                 /** Memoizer for a user’s OpenIDs. */
897                 private final Memoizer<Void> openIdMemoizer = new Memoizer<Void>(new Callable<Void>() {
898
899                         @Override
900                         public Void call() throws Exception {
901                                 if (!hasValue("openIds")) {
902                                         getValue("openIds", Collection.class).set(getOpenIdsByUser(getId()));
903                                 }
904                                 return null;
905                         }
906                 });
907
908                 /**
909                  * Creates a new user.
910                  *
911                  * @param id
912                  *            The ID of the user
913                  */
914                 public LazyUser(String id) {
915                         super(id);
916                 }
917
918                 /**
919                  * {@inheritDoc}
920                  */
921                 @Override
922                 public Collection<String> getOpenIds() {
923                         openIdMemoizer.get();
924                         return super.getOpenIds();
925                 }
926
927         }
928
929         /**
930          * {@link ObjectCreator} implementation that can create {@link User}
931          * objects. This specific implementation creates {@link LazyUser} instances.
932          *
933          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
934          */
935         private class UserCreator implements ObjectCreator<User> {
936
937                 /**
938                  * {@inheritDoc}
939                  */
940                 @Override
941                 public User createObject(ResultSet resultSet) throws SQLException {
942                         return new LazyUser(resultSet.getString("USERS.ID")).setName(resultSet.getString("USERS.NAME")).setPasswordHash(resultSet.getString("USERS.PASSWORD")).setLevel(resultSet.getInt("USERS.LEVEL"));
943                 }
944
945         }
946
947 }