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