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