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