Add method to load properties for arbitrary objects.
[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 loadProperties(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 loadProperties(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 loadProperties(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 loadProperties(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 loadProperties(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 loadProperties(final Artist artist) throws DatabaseException {
244                 Query query = new Query(Type.SELECT, "ARTIST_PROPERTIES");
245                 query.addField(new Field("ARTIST_PROPERTIES.PROPERTY"));
246                 query.addField(new Field("ARTIST_PROPERTIES.VALUE"));
247                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("ARTIST", new StringParameter(artist.getId()))));
248                 database.process(query, new ResultProcessor() {
249
250                         @Override
251                         public void processResult(ResultSet resultSet) throws SQLException {
252                                 if (resultSet.isFirst()) {
253                                         artist.getProperties().removeAll();
254                                 }
255                                 artist.getProperties().set(resultSet.getString("ARTIST_PROPERTIES.PROPERTY"), resultSet.getString("ARTIST_PROPERTIES.VALUE"));
256                         }
257
258                 });
259                 return artist;
260         }
261
262         /**
263          * Loads the properties of all given artists.
264          *
265          * @param artists
266          *            The artists to load the properties for
267          * @return The list of artists
268          * @throws DatabaseException
269          *             if a database error occurs
270          */
271         public List<Artist> loadProperties(List<Artist> artists) throws DatabaseException {
272                 for (Artist artist : artists) {
273                         loadProperties(artist);
274                 }
275                 return artists;
276         }
277
278         /**
279          * Returns all remix artists involved in the track with the given ID.
280          *
281          * @param trackId
282          *            The ID of the track
283          * @return All remix artists involved in the track, in preferred order
284          * @throws DatabaseException
285          *             if a database error occurs
286          */
287         public List<Artist> getRemixArtistsByTrack(String trackId) throws DatabaseException {
288                 Query query = new Query(Type.SELECT, "ARTISTS");
289                 query.addField(new Field("ARTISTS.*"));
290                 query.addJoin(new Join(JoinType.INNER, "TRACK_REMIX_ARTISTS", new Field("TRACK_REMIX_ARTISTS.ARTIST"), new Field("ARTISTS.ID")));
291                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_REMIX_ARTISTS.TRACK", new StringParameter(trackId))));
292                 query.addOrderField(new OrderField(new Field("TRACK_REMIX_ARTISTS.DISPLAY_ORDER")));
293                 return database.getMultiple(query, artistCreator);
294         }
295
296         /**
297          * Returns all related tracks for the track with the given ID.
298          *
299          * @param trackId
300          *            The ID of the tracks
301          * @return A mapping from relationship to all tracks that match the relation
302          * @throws DatabaseException
303          *             if a database error occurs
304          */
305         public Map<Relationship, Collection<Track>> getRelatedTracksByTrack(String trackId) throws DatabaseException {
306                 Query query = new Query(Type.SELECT, "TRACKS");
307                 query.addField(new Field("TRACKS.*"));
308                 query.addField(new Field("TRACK_RELATIONS.*"));
309                 query.addJoin(new Join(JoinType.INNER, "TRACK_RELATIONS", new Field("TRACK_RELATIONS.TRACK"), new Field("TRACK_RELATIONS.RELATED_TRACK")));
310                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_RELATIONS.TRACK", new StringParameter(trackId))));
311                 final Map<Relationship, Collection<Track>> relatedTracks = new EnumMap<Relationship, Collection<Track>>(Relationship.class);
312                 database.process(query, new ResultProcessor() {
313
314                         @Override
315                         @SuppressWarnings("synthetic-access")
316                         public void processResult(ResultSet resultSet) throws SQLException {
317                                 Track track = trackCreator.createObject(resultSet);
318                                 Relationship relationship = Relationship.valueOf(resultSet.getString("TRACK_RELATIONS.RELATIONSHIP"));
319                                 if (!relatedTracks.containsKey(relationship)) {
320                                         relatedTracks.put(relationship, new HashSet<Track>());
321                                 }
322                                 relatedTracks.get(relationship).add(track);
323                         }
324                 });
325                 return relatedTracks;
326         }
327
328         /**
329          * Returns the track with the given ID.
330          *
331          * @param id
332          *            The ID of the track
333          * @return The track with the given ID, or {@code null} if there is no such
334          *         track
335          * @throws DatabaseException
336          *             if a database error occurs
337          */
338         public Track getTrackById(String id) throws DatabaseException {
339                 Query query = new Query(Type.SELECT, "TRACKS");
340                 query.addField(new Field("TRACKS.*"));
341                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACKS.ID", new StringParameter(id))));
342                 return database.getSingle(query, trackCreator);
343         }
344
345         /**
346          * Returns all tracks by the artist with the given ID.
347          *
348          * @param artistId
349          *            The ID of the artist
350          * @return All tracks by the given artist
351          * @throws DatabaseException
352          *             if a database error occurs
353          */
354         public Collection<Track> getTracksByArtist(String artistId) throws DatabaseException {
355                 Query query = new Query(Type.SELECT, "TRACKS");
356                 query.addField(new Field("TRACKS.*"));
357                 query.addJoin(new Join(JoinType.INNER, "TRACK_ARTISTS", new Field("TRACKS.ID"), new Field("TRACK_ARTISTS.TRACK")));
358                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_ARTISTS.ARTIST", new StringParameter(artistId))));
359                 return database.getMultiple(query, trackCreator);
360         }
361
362         /**
363          * Returns all groups the artist with the given ID belongs to.
364          *
365          * @param artistId
366          *            The ID of the artist
367          * @return All groups the artist belongs to
368          * @throws DatabaseException
369          *             if a database error occurs
370          */
371         public Collection<Group> getGroupsByArtist(String artistId) throws DatabaseException {
372                 Query query = new Query(Type.SELECT, "GROUPS");
373                 query.addField(new Field("GROUPS.*"));
374                 query.addJoin(new Join(JoinType.INNER, "GROUP_ARTISTS", new Field("GROUPS.ID"), new Field("GROUP_ARTISTS.GROUP_")));
375                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUP_ARTISTS.ARTIST", new StringParameter(artistId))));
376                 return database.getMultiple(query, groupCreator);
377         }
378
379         /**
380          * Returns all styles for the track with the given ID.
381          *
382          * @param trackId
383          *            The ID of the track
384          * @return All styles for the given track
385          * @throws DatabaseException
386          *             if a database error occurs
387          */
388         public Collection<Style> getStylesByTrack(String trackId) throws DatabaseException {
389                 Query query = new Query(Type.SELECT, "STYLES");
390                 query.addField(new Field("STYLES.*"));
391                 query.addJoin(new Join(JoinType.INNER, "TRACK_STYLES", new Field("STYLES.ID"), new Field("TRACK_STYLES.STYLE")));
392                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_STYLES.TRACK", new StringParameter(trackId))));
393                 return database.getMultiple(query, styleCreator);
394         }
395
396         /**
397          * Returns the user with the given name.
398          *
399          * @param username
400          *            The name of the user
401          * @return The user, or {@code null} if the user does not exist
402          * @throws DatabaseException
403          *             if a database error occurs
404          */
405         public User getUserByName(String username) throws DatabaseException {
406                 Query query = new Query(Type.SELECT, "USERS");
407                 query.addField(new Field("USERS.*"));
408                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USERS.NAME", new StringParameter(username))));
409                 return database.getSingle(query, userCreator);
410         }
411
412         /**
413          * Returns the user connected with the given OpenID.
414          *
415          * @param openId
416          *            The OpenID to find the user for
417          * @return The user connected with the given OpenID, or {@code null} if
418          *         there is no such user
419          * @throws DatabaseException
420          *             if a database error occurs
421          */
422         public User getUserByOpenId(String openId) throws DatabaseException {
423                 Query query = new Query(Type.SELECT, "USERS");
424                 query.addField(new Field("USERS.*"));
425                 query.addJoin(new Join(JoinType.INNER, "USER_OPENIDS", new Field("USER_OPENIDS.USER"), new Field("USERS.ID")));
426                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.OPENID", new StringParameter(openId))));
427                 return database.getSingle(query, userCreator);
428         }
429
430         /**
431          * Returns all OpenIDs connected with the user with the given ID.
432          *
433          * @param userId
434          *            The ID of the user
435          * @return All OpenIDs connected with the given user
436          * @throws DatabaseException
437          *             if a database error occurs
438          */
439         public Collection<String> getOpenIdsByUser(String userId) throws DatabaseException {
440                 Query query = new Query(Type.SELECT, "USER_OPENIDS");
441                 query.addField(new Field("USER_OPENIDS.*"));
442                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.USER", new StringParameter(userId))));
443                 return database.getMultiple(query, new StringCreator("USER_OPENIDS.OPENID"));
444         }
445
446         //
447         // PRIVATE METHODS
448         //
449
450         /**
451          * Loads the properties for the given object.
452          *
453          * @param <T>
454          *            The type of the object
455          * @param object
456          *            The object
457          * @param table
458          *            The table to load the properties from
459          * @param type
460          *            The type of the object (“ARTIST,” “TRACK,” etc.)
461          * @return The object with its properties loaded
462          * @throws DatabaseException
463          *             if a database error occurs
464          */
465         private <T extends Base> T loadProperties(final T object, final String table, String type) throws DatabaseException {
466                 Query query = new Query(Type.SELECT, table);
467                 query.addField(new Field(table + ".PROPERTY"));
468                 query.addField(new Field(table + ".VALUE"));
469                 query.addWhereClause(new ValueFieldWhereClause(new ValueField(type, new StringParameter(object.getId()))));
470                 database.process(query, new ResultProcessor() {
471
472                         @Override
473                         public void processResult(ResultSet resultSet) throws SQLException {
474                                 if (resultSet.isFirst()) {
475                                         object.getProperties().removeAll();
476                                 }
477                                 object.getProperties().set(resultSet.getString(table + ".PROPERTY"), resultSet.getString(table + ".VALUE"));
478                         }
479
480                 });
481                 return object;
482         }
483
484         /**
485          * {@link Artist} implementation that retrieves some attributes (such as
486          * {@link #getGroups()}, and {@link #getTracks()}) from the
487          * {@link DataManager} on demand.
488          *
489          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
490          */
491         private class LazyArtist extends DefaultArtist {
492
493                 /** Memoizer for the tracks by this artist. */
494                 private final Memoizer<Void> tracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
495                         @Override
496                         public Void call() throws DatabaseException {
497                                 if (!hasValue("tracks")) {
498                                         getValue("tracks", Collection.class).set(getTracksByArtist(getId()));
499                                 }
500                                 return null;
501                         }
502                 });
503
504                 /** Memoizer for the groups of this artist. */
505                 private final Memoizer<Void> groupsMemoizer = new Memoizer<Void>(new Callable<Void>() {
506
507                         @Override
508                         public Void call() throws Exception {
509                                 if (!hasValue("groups")) {
510                                         getValue("groups", Collection.class).set(getGroupsByArtist(getId()));
511                                 }
512                                 return null;
513                         }
514
515                 });
516
517                 /**
518                  * Creates a new lazy artist.
519                  *
520                  * @param id
521                  *            The ID of the artist
522                  */
523                 public LazyArtist(String id) {
524                         super(id);
525                 }
526
527                 //
528                 // DEFAULTARTIST METHODS
529                 //
530
531                 /**
532                  * {@inheritDoc}
533                  */
534                 @Override
535                 public Collection<Group> getGroups() {
536                         groupsMemoizer.get();
537                         return super.getGroups();
538                 }
539
540                 /**
541                  * {@inheritDoc}
542                  */
543                 @Override
544                 public Collection<Track> getTracks() {
545                         tracksMemoizer.get();
546                         return super.getTracks();
547                 }
548
549         }
550
551         /**
552          * {@link ObjectCreator} implementation that can create {@link Artist}
553          * objects. This specific class actually creates {@link LazyArtist}
554          * instances.
555          *
556          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
557          */
558         private class ArtistCreator implements ObjectCreator<Artist> {
559
560                 /**
561                  * {@inheritDoc}
562                  */
563                 @Override
564                 public Artist createObject(ResultSet resultSet) throws SQLException {
565                         return new LazyArtist(resultSet.getString("ARTISTS.ID")).setName(resultSet.getString("ARTISTS.NAME"));
566                 }
567
568         }
569
570         /**
571          * {@link Group} implementation that retrieves some attributes (such as
572          * {@link #getArtists()}) from the {@link DataManager} on demand.
573          *
574          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
575          */
576         private class LazyGroup extends DefaultGroup {
577
578                 /** Memoizer for the artist. */
579                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
580
581                         @Override
582                         public Void call() throws Exception {
583                                 if (!hasValue("artists")) {
584                                         getValue("artists", Collection.class).set(getArtistsByGroup(getId()));
585                                 }
586                                 return null;
587                         }
588
589                 });
590
591                 /**
592                  * Creates a new lazy group.
593                  *
594                  * @param id
595                  *            The ID of the group
596                  */
597                 public LazyGroup(String id) {
598                         super(id);
599                 }
600
601                 //
602                 // DEFAULTGROUP METHODS
603                 //
604
605                 /**
606                  * {@inheritDoc}
607                  */
608                 @Override
609                 public Collection<Artist> getArtists() {
610                         artistsMemoizer.get();
611                         return super.getArtists();
612                 }
613
614         }
615
616         /**
617          * {@link ObjectCreator} implementation that can create {@link Group}
618          * objects. This specific implementation creates {@link LazyGroup}
619          * instances.
620          *
621          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
622          */
623         private class GroupCreator implements ObjectCreator<Group> {
624
625                 /**
626                  * {@inheritDoc}
627                  */
628                 @Override
629                 public Group createObject(ResultSet resultSet) throws SQLException {
630                         return new LazyGroup(resultSet.getString("GROUPS.ID")).setName(resultSet.getString("GROUPS.NAME")).setUrl(resultSet.getString("GROUPS.URL"));
631                 }
632
633         }
634
635         /**
636          * {@link Track} implementation that retrieves some attributes (such as
637          * {@link #getArtists()}, and {@link #getStyles()}) from the
638          * {@link DataManager} on demand.
639          *
640          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
641          */
642         private class LazyTrack extends DefaultTrack {
643
644                 /** Memoizer for the artists. */
645                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
646
647                         @Override
648                         public Void call() throws Exception {
649                                 if (!hasValue("artists")) {
650                                         getValue("artists", List.class).set(getArtistsByTrack(getId()));
651                                 }
652                                 return null;
653                         }
654
655                 });
656
657                 /** Memoizer for the styles. */
658                 private final Memoizer<Void> stylesMemoizer = new Memoizer<Void>(new Callable<Void>() {
659
660                         @Override
661                         public Void call() throws Exception {
662                                 if (!hasValue("styles")) {
663                                         getValue("styles", Collection.class).set(getStylesByTrack(getId()));
664                                 }
665                                 return null;
666                         }
667
668                 });
669
670                 /** Memoizer for the remix artists. */
671                 private final Memoizer<Void> remixArtistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
672
673                         @Override
674                         public Void call() throws Exception {
675                                 if (!hasValue("remixArtists")) {
676                                         getValue("remixArtists", List.class).set(getRemixArtistsByTrack(getId()));
677                                 }
678                                 return null;
679                         }
680
681                 });
682
683                 /** Memoizer for the related tracks. */
684                 private final Memoizer<Void> relatedTracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
685
686                         @Override
687                         public Void call() throws Exception {
688                                 if (!hasValue("relatedTracks")) {
689                                         getValue("relatedTracks", Map.class).set(getRelatedTracksByTrack(getId()));
690                                 }
691                                 return null;
692                         }
693                 });
694
695                 /**
696                  * Creates a new track.
697                  *
698                  * @param id
699                  *            The ID of the track
700                  */
701                 public LazyTrack(String id) {
702                         super(id);
703                 }
704
705                 //
706                 // DEFAULTTRACK METHODS
707                 //
708
709                 /**
710                  * {@inheritDoc}
711                  */
712                 @Override
713                 public List<Artist> getArtists() {
714                         artistsMemoizer.get();
715                         return super.getArtists();
716                 }
717
718                 /**
719                  * {@inheritDoc}
720                  */
721                 @Override
722                 public Collection<Style> getStyles() {
723                         stylesMemoizer.get();
724                         return super.getStyles();
725                 }
726
727                 /**
728                  * {@inheritDoc}
729                  */
730                 @Override
731                 public List<Artist> getRemixArtists() {
732                         remixArtistsMemoizer.get();
733                         return super.getRemixArtists();
734                 }
735
736                 /**
737                  * {@inheritDoc}
738                  */
739                 @Override
740                 public Map<Relationship, Collection<Track>> getRelatedTracks() {
741                         relatedTracksMemoizer.get();
742                         return super.getRelatedTracks();
743                 }
744
745         }
746
747         /**
748          * {@link ObjectCreator} implementation that can create {@link Track}
749          * objects. This specific implementation creates {@link LazyTrack}
750          * instances.
751          *
752          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
753          */
754         private class TrackCreator implements ObjectCreator<Track> {
755
756                 /**
757                  * {@inheritDoc}
758                  */
759                 @Override
760                 public Track createObject(ResultSet resultSet) throws SQLException {
761                         return new LazyTrack(resultSet.getString("TRACKS.ID")).setName(resultSet.getString("TRACKS.NAME")).setRemix(resultSet.getString("TRACKS.REMIX"));
762                 }
763
764         }
765
766         /**
767          * {@link ObjectCreator} implementation that can create
768          * {@link TrackDerivative} objects.
769          *
770          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
771          */
772         private class TrackDerivativeCreator implements ObjectCreator<TrackDerivative> {
773
774                 /**
775                  * {@inheritDoc}
776                  */
777                 @Override
778                 public TrackDerivative createObject(ResultSet resultSet) throws SQLException {
779                         return new DefaultTrackDerivative(resultSet.getString("TRACK_DERIVATIVES.ID"));
780                 }
781
782         }
783
784         /**
785          * {@link ObjectCreator} implementation that can create {@link Style}
786          * objects.
787          *
788          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
789          */
790         private class StyleCreator implements ObjectCreator<Style> {
791
792                 /**
793                  * {@inheritDoc}
794                  */
795                 @Override
796                 public Style createObject(ResultSet resultSet) throws SQLException {
797                         return new DefaultStyle(resultSet.getString("STYLES.ID")).setName(resultSet.getString("STYLES.NAME"));
798                 }
799
800         }
801
802         /**
803          * {@link User} implementation that retrieves some attributes (such as
804          * {@link #getOpenIds()}) from the {@link DataManager} on demand.
805          *
806          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
807          */
808         private class LazyUser extends DefaultUser {
809
810                 /** Memoizer for a user’s OpenIDs. */
811                 private final Memoizer<Void> openIdMemoizer = new Memoizer<Void>(new Callable<Void>() {
812
813                         @Override
814                         public Void call() throws Exception {
815                                 if (!hasValue("openIds")) {
816                                         getValue("openIds", Collection.class).set(getOpenIdsByUser(getId()));
817                                 }
818                                 return null;
819                         }
820                 });
821
822                 /**
823                  * Creates a new user.
824                  *
825                  * @param id
826                  *            The ID of the user
827                  */
828                 public LazyUser(String id) {
829                         super(id);
830                 }
831
832                 /**
833                  * {@inheritDoc}
834                  */
835                 @Override
836                 public Collection<String> getOpenIds() {
837                         openIdMemoizer.get();
838                         return super.getOpenIds();
839                 }
840
841         }
842
843         /**
844          * {@link ObjectCreator} implementation that can create {@link User}
845          * objects. This specific implementation creates {@link LazyUser} instances.
846          *
847          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
848          */
849         private class UserCreator implements ObjectCreator<User> {
850
851                 /**
852                  * {@inheritDoc}
853                  */
854                 @Override
855                 public User createObject(ResultSet resultSet) throws SQLException {
856                         return new LazyUser(resultSet.getString("USERS.ID")).setName(resultSet.getString("USERS.NAME")).setPasswordHash(resultSet.getString("USERS.PASSWORD")).setLevel(resultSet.getInt("USERS.LEVEL"));
857                 }
858
859         }
860
861 }