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