Change method signature.
[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 loadTrackProperties(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 loadTrackProperties(database.getMultiple(query, trackCreator));
345         }
346
347         /**
348          * Loads the properties for the given track.
349          *
350          * @param track
351          *            The track for which to load the properties
352          * @return The track with the properties loaded
353          * @throws DatabaseException
354          *             if a database error occurs
355          */
356         public Track loadTrackProperties(Track track) throws DatabaseException {
357                 return loadProperties(track, "TRACK_PROPERTIES", "TRACK");
358         }
359
360         /**
361          * Loads the properties for the given tracks.
362          *
363          * @param tracks
364          *            The tracks for which to load the properties
365          * @return The tracks with the properties loaded
366          * @throws DatabaseException
367          *             if a database error occurs
368          */
369         public List<Track> loadTrackProperties(List<Track> tracks) throws DatabaseException {
370                 for (Track track : tracks) {
371                         loadTrackProperties(track);
372                 }
373                 return tracks;
374         }
375
376         /**
377          * Creates a new track with the given name.
378          *
379          * @param name
380          *            The name of the track
381          * @return The created track
382          * @throws DatabaseException
383          *             if a database error occurs
384          */
385         public Track createTrack(String name) throws DatabaseException {
386                 Query query = new Query(Type.INSERT, "TRACKS");
387                 String id = UUID.randomUUID().toString();
388                 query.addValueField(new ValueField("ID", new StringParameter(id)));
389                 query.addValueField(new ValueField("NAME", new StringParameter(name)));
390                 database.insert(query);
391                 return getTrackById(id);
392         }
393
394         /**
395          * Returns the derivative with the given ID.
396          *
397          * @param id
398          *            The ID of the derivatives to load
399          * @return The derivative with the given ID
400          * @throws DatabaseException
401          *             if a database error occurs
402          */
403         public TrackDerivative getTrackDerivativeById(String id) throws DatabaseException {
404                 Query query = new Query(Type.SELECT, "TRACK_DERIVATIVES");
405                 query.addField(new Field("TRACK_DERIVATIVES.*"));
406                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_DERIVATIVES.ID", new StringParameter(id))));
407                 return loadTrackDerivativeProperties(database.getSingle(query, trackDerivativeCreator));
408         }
409
410         /**
411          * Returns the derivatives for the given track.
412          *
413          * @param trackId
414          *            The track ID to get the derivatives for
415          * @return The derivatives for the given track
416          * @throws DatabaseException
417          *             if a database error occurs
418          */
419         public Collection<TrackDerivative> getTrackDerivativesByTrack(String trackId) throws DatabaseException {
420                 Query query = new Query(Type.SELECT, "TRACK_DERIVATIVES");
421                 query.addField(new Field("TRACK_DERIVATIVES.*"));
422                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_DERIVATIVES.TRACK", new StringParameter(trackId))));
423                 return loadTrackDerivativeProperties(database.getMultiple(query, trackDerivativeCreator));
424         }
425
426         /**
427          * Creates a new derivative for the given track.
428          *
429          * @param track
430          *            The track to create the derivative for
431          * @return The created derivative
432          * @throws DatabaseException
433          *             if a database error occurs
434          */
435         public TrackDerivative createTrackDerivative(Track track) throws DatabaseException {
436                 Query query = new Query(Type.INSERT, "TRACK_DERIVATIVES");
437                 String id = UUID.randomUUID().toString();
438                 query.addValueField(new ValueField("TRACK_DERIVATIVES.ID", new StringParameter(id)));
439                 query.addValueField(new ValueField("TRACK_DERIVATIVES.TRACK", new StringParameter(track.getId())));
440                 database.insert(query);
441                 return getTrackDerivativeById(id);
442         }
443
444         /**
445          * Loads the properties for the given track derivative.
446          *
447          * @param trackDerivative
448          *            The track derivative to load the properties for
449          * @return The track derivative with its properties loaded
450          * @throws DatabaseException
451          *             if a database error occurs
452          */
453         public TrackDerivative loadTrackDerivativeProperties(TrackDerivative trackDerivative) throws DatabaseException {
454                 return loadProperties(trackDerivative, "TRACK_DERIVATIVE_PROPERTIES", "TRACK_DERIVATIVE");
455         }
456
457         /**
458          * Loads the properties for the given track derivatives.
459          *
460          * @param trackDerivatives
461          *            The track derivatives to load the properties for
462          * @return The track derivatives with their properties loaded
463          * @throws DatabaseException
464          *             if a database error occurs
465          */
466         public List<TrackDerivative> loadTrackDerivativeProperties(List<TrackDerivative> trackDerivatives) throws DatabaseException {
467                 for (TrackDerivative trackDerivative : trackDerivatives) {
468                         loadTrackDerivativeProperties(trackDerivative);
469                 }
470                 return trackDerivatives;
471         }
472
473         /**
474          * Returns all groups the artist with the given ID belongs to.
475          *
476          * @param artistId
477          *            The ID of the artist
478          * @return All groups the artist belongs to
479          * @throws DatabaseException
480          *             if a database error occurs
481          */
482         public Collection<Group> getGroupsByArtist(String artistId) throws DatabaseException {
483                 Query query = new Query(Type.SELECT, "GROUPS");
484                 query.addField(new Field("GROUPS.*"));
485                 query.addJoin(new Join(JoinType.INNER, "GROUP_ARTISTS", new Field("GROUPS.ID"), new Field("GROUP_ARTISTS.GROUP_")));
486                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUP_ARTISTS.ARTIST", new StringParameter(artistId))));
487                 return database.getMultiple(query, groupCreator);
488         }
489
490         /**
491          * Returns all styles for the track with the given ID.
492          *
493          * @param trackId
494          *            The ID of the track
495          * @return All styles for the given track
496          * @throws DatabaseException
497          *             if a database error occurs
498          */
499         public Collection<Style> getStylesByTrack(String trackId) throws DatabaseException {
500                 Query query = new Query(Type.SELECT, "STYLES");
501                 query.addField(new Field("STYLES.*"));
502                 query.addJoin(new Join(JoinType.INNER, "TRACK_STYLES", new Field("STYLES.ID"), new Field("TRACK_STYLES.STYLE")));
503                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_STYLES.TRACK", new StringParameter(trackId))));
504                 return database.getMultiple(query, styleCreator);
505         }
506
507         /**
508          * Returns the user with the given name.
509          *
510          * @param username
511          *            The name of the user
512          * @return The user, or {@code null} if the user does not exist
513          * @throws DatabaseException
514          *             if a database error occurs
515          */
516         public User getUserByName(String username) throws DatabaseException {
517                 Query query = new Query(Type.SELECT, "USERS");
518                 query.addField(new Field("USERS.*"));
519                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USERS.NAME", new StringParameter(username))));
520                 return database.getSingle(query, userCreator);
521         }
522
523         /**
524          * Returns the user connected with the given OpenID.
525          *
526          * @param openId
527          *            The OpenID to find the user for
528          * @return The user connected with the given OpenID, or {@code null} if
529          *         there is no such user
530          * @throws DatabaseException
531          *             if a database error occurs
532          */
533         public User getUserByOpenId(String openId) throws DatabaseException {
534                 Query query = new Query(Type.SELECT, "USERS");
535                 query.addField(new Field("USERS.*"));
536                 query.addJoin(new Join(JoinType.INNER, "USER_OPENIDS", new Field("USER_OPENIDS.USER"), new Field("USERS.ID")));
537                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.OPENID", new StringParameter(openId))));
538                 return database.getSingle(query, userCreator);
539         }
540
541         /**
542          * Returns all OpenIDs connected with the user with the given ID.
543          *
544          * @param userId
545          *            The ID of the user
546          * @return All OpenIDs connected with the given user
547          * @throws DatabaseException
548          *             if a database error occurs
549          */
550         public Collection<String> getOpenIdsByUser(String userId) throws DatabaseException {
551                 Query query = new Query(Type.SELECT, "USER_OPENIDS");
552                 query.addField(new Field("USER_OPENIDS.*"));
553                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.USER", new StringParameter(userId))));
554                 return database.getMultiple(query, new StringCreator("USER_OPENIDS.OPENID"));
555         }
556
557         //
558         // PRIVATE METHODS
559         //
560
561         /**
562          * Loads the properties for the given object.
563          *
564          * @param <T>
565          *            The type of the object
566          * @param object
567          *            The object
568          * @param table
569          *            The table to load the properties from
570          * @param type
571          *            The type of the object (“ARTIST,” “TRACK,” etc.)
572          * @return The object with its properties loaded
573          * @throws DatabaseException
574          *             if a database error occurs
575          */
576         private <T extends Base> T loadProperties(final T object, final String table, String type) throws DatabaseException {
577                 Query query = new Query(Type.SELECT, table);
578                 query.addField(new Field(table + ".PROPERTY"));
579                 query.addField(new Field(table + ".VALUE"));
580                 query.addWhereClause(new ValueFieldWhereClause(new ValueField(type, new StringParameter(object.getId()))));
581                 database.process(query, new ResultProcessor() {
582
583                         @Override
584                         public void processResult(ResultSet resultSet) throws SQLException {
585                                 if (resultSet.isFirst()) {
586                                         object.getProperties().removeAll();
587                                 }
588                                 object.getProperties().set(resultSet.getString(table + ".PROPERTY"), resultSet.getString(table + ".VALUE"));
589                         }
590
591                 });
592                 return object;
593         }
594
595         /**
596          * {@link Artist} implementation that retrieves some attributes (such as
597          * {@link #getGroups()}, and {@link #getTracks()}) from the
598          * {@link DataManager} on demand.
599          *
600          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
601          */
602         private class LazyArtist extends DefaultArtist {
603
604                 /** Memoizer for the tracks by this artist. */
605                 private final Memoizer<Void> tracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
606                         @Override
607                         public Void call() throws DatabaseException {
608                                 if (!hasValue("tracks")) {
609                                         getValue("tracks", Collection.class).set(getTracksByArtist(getId()));
610                                 }
611                                 return null;
612                         }
613                 });
614
615                 /** Memoizer for the groups of this artist. */
616                 private final Memoizer<Void> groupsMemoizer = new Memoizer<Void>(new Callable<Void>() {
617
618                         @Override
619                         public Void call() throws Exception {
620                                 if (!hasValue("groups")) {
621                                         getValue("groups", Collection.class).set(getGroupsByArtist(getId()));
622                                 }
623                                 return null;
624                         }
625
626                 });
627
628                 /**
629                  * Creates a new lazy artist.
630                  *
631                  * @param id
632                  *            The ID of the artist
633                  */
634                 public LazyArtist(String id) {
635                         super(id);
636                 }
637
638                 //
639                 // DEFAULTARTIST METHODS
640                 //
641
642                 /**
643                  * {@inheritDoc}
644                  */
645                 @Override
646                 public Collection<Group> getGroups() {
647                         groupsMemoizer.get();
648                         return super.getGroups();
649                 }
650
651                 /**
652                  * {@inheritDoc}
653                  */
654                 @Override
655                 public Collection<Track> getTracks() {
656                         tracksMemoizer.get();
657                         return super.getTracks();
658                 }
659
660         }
661
662         /**
663          * {@link ObjectCreator} implementation that can create {@link Artist}
664          * objects. This specific class actually creates {@link LazyArtist}
665          * instances.
666          *
667          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
668          */
669         private class ArtistCreator implements ObjectCreator<Artist> {
670
671                 /**
672                  * {@inheritDoc}
673                  */
674                 @Override
675                 public Artist createObject(ResultSet resultSet) throws SQLException {
676                         return new LazyArtist(resultSet.getString("ARTISTS.ID")).setName(resultSet.getString("ARTISTS.NAME"));
677                 }
678
679         }
680
681         /**
682          * {@link Group} implementation that retrieves some attributes (such as
683          * {@link #getArtists()}) from the {@link DataManager} on demand.
684          *
685          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
686          */
687         private class LazyGroup extends DefaultGroup {
688
689                 /** Memoizer for the artist. */
690                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
691
692                         @Override
693                         public Void call() throws Exception {
694                                 if (!hasValue("artists")) {
695                                         getValue("artists", Collection.class).set(getArtistsByGroup(getId()));
696                                 }
697                                 return null;
698                         }
699
700                 });
701
702                 /**
703                  * Creates a new lazy group.
704                  *
705                  * @param id
706                  *            The ID of the group
707                  */
708                 public LazyGroup(String id) {
709                         super(id);
710                 }
711
712                 //
713                 // DEFAULTGROUP METHODS
714                 //
715
716                 /**
717                  * {@inheritDoc}
718                  */
719                 @Override
720                 public Collection<Artist> getArtists() {
721                         artistsMemoizer.get();
722                         return super.getArtists();
723                 }
724
725         }
726
727         /**
728          * {@link ObjectCreator} implementation that can create {@link Group}
729          * objects. This specific implementation creates {@link LazyGroup}
730          * instances.
731          *
732          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
733          */
734         private class GroupCreator implements ObjectCreator<Group> {
735
736                 /**
737                  * {@inheritDoc}
738                  */
739                 @Override
740                 public Group createObject(ResultSet resultSet) throws SQLException {
741                         return new LazyGroup(resultSet.getString("GROUPS.ID")).setName(resultSet.getString("GROUPS.NAME")).setUrl(resultSet.getString("GROUPS.URL"));
742                 }
743
744         }
745
746         /**
747          * {@link Track} implementation that retrieves some attributes (such as
748          * {@link #getArtists()}, and {@link #getStyles()}) from the
749          * {@link DataManager} on demand.
750          *
751          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
752          */
753         private class LazyTrack extends DefaultTrack {
754
755                 /** Memoizer for the artists. */
756                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
757
758                         @Override
759                         public Void call() throws Exception {
760                                 if (!hasValue("artists")) {
761                                         getValue("artists", List.class).set(getArtistsByTrack(getId()));
762                                 }
763                                 return null;
764                         }
765
766                 });
767
768                 /** Memoizer for the styles. */
769                 private final Memoizer<Void> stylesMemoizer = new Memoizer<Void>(new Callable<Void>() {
770
771                         @Override
772                         public Void call() throws Exception {
773                                 if (!hasValue("styles")) {
774                                         getValue("styles", Collection.class).set(getStylesByTrack(getId()));
775                                 }
776                                 return null;
777                         }
778
779                 });
780
781                 /** Memoizer for the remix artists. */
782                 private final Memoizer<Void> remixArtistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
783
784                         @Override
785                         public Void call() throws Exception {
786                                 if (!hasValue("remixArtists")) {
787                                         getValue("remixArtists", List.class).set(getRemixArtistsByTrack(getId()));
788                                 }
789                                 return null;
790                         }
791
792                 });
793
794                 /** Memoizer for the track derivatives. */
795                 private final Memoizer<Void> derivativesMemoizer = new Memoizer<Void>(new Callable<Void>() {
796
797                         @Override
798                         public Void call() throws Exception {
799                                 if (!hasValue("derivatives")) {
800                                         getValue("derivatives", Collection.class).set(getTrackDerivativesByTrack(getId()));
801                                 }
802                                 return null;
803                         }
804
805                 });
806
807                 /** Memoizer for the related tracks. */
808                 private final Memoizer<Void> relatedTracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
809
810                         @Override
811                         public Void call() throws Exception {
812                                 if (!hasValue("relatedTracks")) {
813                                         getValue("relatedTracks", Map.class).set(getRelatedTracksByTrack(getId()));
814                                 }
815                                 return null;
816                         }
817                 });
818
819                 /**
820                  * Creates a new track.
821                  *
822                  * @param id
823                  *            The ID of the track
824                  */
825                 public LazyTrack(String id) {
826                         super(id);
827                 }
828
829                 //
830                 // DEFAULTTRACK METHODS
831                 //
832
833                 /**
834                  * {@inheritDoc}
835                  */
836                 @Override
837                 public List<Artist> getArtists() {
838                         artistsMemoizer.get();
839                         return super.getArtists();
840                 }
841
842                 /**
843                  * {@inheritDoc}
844                  */
845                 @Override
846                 public Collection<Style> getStyles() {
847                         stylesMemoizer.get();
848                         return super.getStyles();
849                 }
850
851                 /**
852                  * {@inheritDoc}
853                  */
854                 @Override
855                 public List<Artist> getRemixArtists() {
856                         remixArtistsMemoizer.get();
857                         return super.getRemixArtists();
858                 }
859
860                 /**
861                  * {@inheritDoc}
862                  */
863                 @Override
864                 public Collection<TrackDerivative> getDerivatives() {
865                         derivativesMemoizer.get();
866                         return super.getDerivatives();
867                 }
868
869                 /**
870                  * {@inheritDoc}
871                  */
872                 @Override
873                 public Map<Relationship, Collection<Track>> getRelatedTracks() {
874                         relatedTracksMemoizer.get();
875                         return super.getRelatedTracks();
876                 }
877
878         }
879
880         /**
881          * {@link ObjectCreator} implementation that can create {@link Track}
882          * objects. This specific implementation creates {@link LazyTrack}
883          * instances.
884          *
885          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
886          */
887         private class TrackCreator implements ObjectCreator<Track> {
888
889                 /**
890                  * {@inheritDoc}
891                  */
892                 @Override
893                 public Track createObject(ResultSet resultSet) throws SQLException {
894                         return new LazyTrack(resultSet.getString("TRACKS.ID")).setName(resultSet.getString("TRACKS.NAME")).setRemix(resultSet.getString("TRACKS.REMIX"));
895                 }
896
897         }
898
899         /**
900          * {@link ObjectCreator} implementation that can create
901          * {@link TrackDerivative} objects.
902          *
903          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
904          */
905         private class TrackDerivativeCreator implements ObjectCreator<TrackDerivative> {
906
907                 /**
908                  * {@inheritDoc}
909                  */
910                 @Override
911                 public TrackDerivative createObject(ResultSet resultSet) throws SQLException {
912                         return new DefaultTrackDerivative(resultSet.getString("TRACK_DERIVATIVES.ID"));
913                 }
914
915         }
916
917         /**
918          * {@link ObjectCreator} implementation that can create {@link Style}
919          * objects.
920          *
921          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
922          */
923         private class StyleCreator implements ObjectCreator<Style> {
924
925                 /**
926                  * {@inheritDoc}
927                  */
928                 @Override
929                 public Style createObject(ResultSet resultSet) throws SQLException {
930                         return new DefaultStyle(resultSet.getString("STYLES.ID")).setName(resultSet.getString("STYLES.NAME"));
931                 }
932
933         }
934
935         /**
936          * {@link User} implementation that retrieves some attributes (such as
937          * {@link #getOpenIds()}) from the {@link DataManager} on demand.
938          *
939          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
940          */
941         private class LazyUser extends DefaultUser {
942
943                 /** Memoizer for a user’s OpenIDs. */
944                 private final Memoizer<Void> openIdMemoizer = new Memoizer<Void>(new Callable<Void>() {
945
946                         @Override
947                         public Void call() throws Exception {
948                                 if (!hasValue("openIds")) {
949                                         getValue("openIds", Collection.class).set(getOpenIdsByUser(getId()));
950                                 }
951                                 return null;
952                         }
953                 });
954
955                 /**
956                  * Creates a new user.
957                  *
958                  * @param id
959                  *            The ID of the user
960                  */
961                 public LazyUser(String id) {
962                         super(id);
963                 }
964
965                 /**
966                  * {@inheritDoc}
967                  */
968                 @Override
969                 public Collection<String> getOpenIds() {
970                         openIdMemoizer.get();
971                         return super.getOpenIds();
972                 }
973
974         }
975
976         /**
977          * {@link ObjectCreator} implementation that can create {@link User}
978          * objects. This specific implementation creates {@link LazyUser} instances.
979          *
980          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
981          */
982         private class UserCreator implements ObjectCreator<User> {
983
984                 /**
985                  * {@inheritDoc}
986                  */
987                 @Override
988                 public User createObject(ResultSet resultSet) throws SQLException {
989                         return new LazyUser(resultSet.getString("USERS.ID")).setName(resultSet.getString("USERS.NAME")).setPasswordHash(resultSet.getString("USERS.PASSWORD")).setLevel(resultSet.getInt("USERS.LEVEL"));
990                 }
991
992         }
993
994 }