ad01bfed79d7c7c561649aabaac3ed75baea347a
[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          * Returns all groups the artist with the given ID belongs to.
519          *
520          * @param artistId
521          *            The ID of the artist
522          * @return All groups the artist belongs to
523          * @throws DatabaseException
524          *             if a database error occurs
525          */
526         public Collection<Group> getGroupsByArtist(String artistId) throws DatabaseException {
527                 Query query = new Query(Type.SELECT, "GROUPS");
528                 query.addField(new Field("GROUPS.*"));
529                 query.addJoin(new Join(JoinType.INNER, "GROUP_ARTISTS", new Field("GROUPS.ID"), new Field("GROUP_ARTISTS.GROUP_")));
530                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUP_ARTISTS.ARTIST", new StringParameter(artistId))));
531                 return database.getMultiple(query, groupCreator);
532         }
533
534         /**
535          * Returns all styles for the track with the given ID.
536          *
537          * @param trackId
538          *            The ID of the track
539          * @return All styles for the given track
540          * @throws DatabaseException
541          *             if a database error occurs
542          */
543         public Collection<Style> getStylesByTrack(String trackId) throws DatabaseException {
544                 Query query = new Query(Type.SELECT, "STYLES");
545                 query.addField(new Field("STYLES.*"));
546                 query.addJoin(new Join(JoinType.INNER, "TRACK_STYLES", new Field("STYLES.ID"), new Field("TRACK_STYLES.STYLE")));
547                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_STYLES.TRACK", new StringParameter(trackId))));
548                 return database.getMultiple(query, styleCreator);
549         }
550
551         /**
552          * Returns the user with the given name.
553          *
554          * @param username
555          *            The name of the user
556          * @return The user, or {@code null} if the user does not exist
557          * @throws DatabaseException
558          *             if a database error occurs
559          */
560         public User getUserByName(String username) throws DatabaseException {
561                 Query query = new Query(Type.SELECT, "USERS");
562                 query.addField(new Field("USERS.*"));
563                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USERS.NAME", new StringParameter(username))));
564                 return database.getSingle(query, userCreator);
565         }
566
567         /**
568          * Returns the user connected with the given OpenID.
569          *
570          * @param openId
571          *            The OpenID to find the user for
572          * @return The user connected with the given OpenID, or {@code null} if
573          *         there is no such user
574          * @throws DatabaseException
575          *             if a database error occurs
576          */
577         public User getUserByOpenId(String openId) throws DatabaseException {
578                 Query query = new Query(Type.SELECT, "USERS");
579                 query.addField(new Field("USERS.*"));
580                 query.addJoin(new Join(JoinType.INNER, "USER_OPENIDS", new Field("USER_OPENIDS.USER"), new Field("USERS.ID")));
581                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.OPENID", new StringParameter(openId))));
582                 return database.getSingle(query, userCreator);
583         }
584
585         /**
586          * Returns all OpenIDs connected with the user with the given ID.
587          *
588          * @param userId
589          *            The ID of the user
590          * @return All OpenIDs connected with the given user
591          * @throws DatabaseException
592          *             if a database error occurs
593          */
594         public Collection<String> getOpenIdsByUser(String userId) throws DatabaseException {
595                 Query query = new Query(Type.SELECT, "USER_OPENIDS");
596                 query.addField(new Field("USER_OPENIDS.*"));
597                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.USER", new StringParameter(userId))));
598                 return database.getMultiple(query, new StringCreator("USER_OPENIDS.OPENID"));
599         }
600
601         //
602         // PRIVATE METHODS
603         //
604
605         /**
606          * Loads the properties for the given object.
607          *
608          * @param <T>
609          *            The type of the object
610          * @param object
611          *            The object
612          * @param table
613          *            The table to load the properties from
614          * @param type
615          *            The type of the object (“ARTIST,” “TRACK,” etc.)
616          * @return The object with its properties loaded
617          * @throws DatabaseException
618          *             if a database error occurs
619          */
620         private <T extends Base> T loadProperties(final T object, final String table, String type) throws DatabaseException {
621                 Query query = new Query(Type.SELECT, table);
622                 query.addField(new Field(table + ".PROPERTY"));
623                 query.addField(new Field(table + ".VALUE"));
624                 query.addWhereClause(new ValueFieldWhereClause(new ValueField(type, new StringParameter(object.getId()))));
625                 database.process(query, new ResultProcessor() {
626
627                         @Override
628                         public void processResult(ResultSet resultSet) throws SQLException {
629                                 if (resultSet.isFirst()) {
630                                         object.getProperties().removeAll();
631                                 }
632                                 object.getProperties().set(resultSet.getString(table + ".PROPERTY"), resultSet.getString(table + ".VALUE"));
633                         }
634
635                 });
636                 return object;
637         }
638
639         /**
640          * {@link Artist} implementation that retrieves some attributes (such as
641          * {@link #getGroups()}, and {@link #getTracks()}) from the
642          * {@link DataManager} on demand.
643          *
644          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
645          */
646         private class LazyArtist extends DefaultArtist {
647
648                 /** Memoizer for the tracks by this artist. */
649                 private final Memoizer<Void> tracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
650
651                         @Override
652                         public Void call() throws DatabaseException {
653                                 if (!hasValue("tracks")) {
654                                         getValue("tracks", Collection.class).set(getTracksByArtist(getId()));
655                                 }
656                                 return null;
657                         }
658                 });
659
660                 /** Memoizer for the groups of this artist. */
661                 private final Memoizer<Void> groupsMemoizer = new Memoizer<Void>(new Callable<Void>() {
662
663                         @Override
664                         public Void call() throws Exception {
665                                 if (!hasValue("groups")) {
666                                         getValue("groups", Collection.class).set(getGroupsByArtist(getId()));
667                                 }
668                                 return null;
669                         }
670
671                 });
672
673                 /**
674                  * Creates a new lazy artist.
675                  *
676                  * @param id
677                  *            The ID of the artist
678                  */
679                 public LazyArtist(String id) {
680                         super(id);
681                 }
682
683                 //
684                 // DEFAULTARTIST METHODS
685                 //
686
687                 /**
688                  * {@inheritDoc}
689                  */
690                 @Override
691                 public Collection<Group> getGroups() {
692                         groupsMemoizer.get();
693                         return super.getGroups();
694                 }
695
696                 /**
697                  * {@inheritDoc}
698                  */
699                 @Override
700                 public Collection<Track> getTracks() {
701                         tracksMemoizer.get();
702                         return super.getTracks();
703                 }
704
705         }
706
707         /**
708          * {@link ObjectCreator} implementation that can create {@link Artist}
709          * objects. This specific class actually creates {@link LazyArtist}
710          * instances.
711          *
712          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
713          */
714         private class ArtistCreator implements ObjectCreator<Artist> {
715
716                 /**
717                  * {@inheritDoc}
718                  */
719                 @Override
720                 public Artist createObject(ResultSet resultSet) throws SQLException {
721                         return new LazyArtist(resultSet.getString("ARTISTS.ID")).setName(resultSet.getString("ARTISTS.NAME"));
722                 }
723
724         }
725
726         /**
727          * {@link Group} implementation that retrieves some attributes (such as
728          * {@link #getArtists()}) from the {@link DataManager} on demand.
729          *
730          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
731          */
732         private class LazyGroup extends DefaultGroup {
733
734                 /** Memoizer for the artist. */
735                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
736
737                         @Override
738                         public Void call() throws Exception {
739                                 if (!hasValue("artists")) {
740                                         getValue("artists", Collection.class).set(getArtistsByGroup(getId()));
741                                 }
742                                 return null;
743                         }
744
745                 });
746
747                 /**
748                  * Creates a new lazy group.
749                  *
750                  * @param id
751                  *            The ID of the group
752                  */
753                 public LazyGroup(String id) {
754                         super(id);
755                 }
756
757                 //
758                 // DEFAULTGROUP METHODS
759                 //
760
761                 /**
762                  * {@inheritDoc}
763                  */
764                 @Override
765                 public Collection<Artist> getArtists() {
766                         artistsMemoizer.get();
767                         return super.getArtists();
768                 }
769
770         }
771
772         /**
773          * {@link ObjectCreator} implementation that can create {@link Group}
774          * objects. This specific implementation creates {@link LazyGroup}
775          * instances.
776          *
777          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
778          */
779         private class GroupCreator implements ObjectCreator<Group> {
780
781                 /**
782                  * {@inheritDoc}
783                  */
784                 @Override
785                 public Group createObject(ResultSet resultSet) throws SQLException {
786                         return new LazyGroup(resultSet.getString("GROUPS.ID")).setName(resultSet.getString("GROUPS.NAME")).setUrl(resultSet.getString("GROUPS.URL"));
787                 }
788
789         }
790
791         /**
792          * {@link Track} implementation that retrieves some attributes (such as
793          * {@link #getArtists()}, and {@link #getStyles()}) from the
794          * {@link DataManager} on demand.
795          *
796          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
797          */
798         private class LazyTrack extends DefaultTrack {
799
800                 /** Memoizer for the artists. */
801                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
802
803                         @Override
804                         public Void call() throws Exception {
805                                 if (!hasValue("artists")) {
806                                         getValue("artists", List.class).set(getArtistsByTrack(getId()));
807                                 }
808                                 return null;
809                         }
810
811                 });
812
813                 /** Memoizer for the styles. */
814                 private final Memoizer<Void> stylesMemoizer = new Memoizer<Void>(new Callable<Void>() {
815
816                         @Override
817                         public Void call() throws Exception {
818                                 if (!hasValue("styles")) {
819                                         getValue("styles", Collection.class).set(getStylesByTrack(getId()));
820                                 }
821                                 return null;
822                         }
823
824                 });
825
826                 /** Memoizer for the remix artists. */
827                 private final Memoizer<Void> remixArtistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
828
829                         @Override
830                         public Void call() throws Exception {
831                                 if (!hasValue("remixArtists")) {
832                                         getValue("remixArtists", List.class).set(getRemixArtistsByTrack(getId()));
833                                 }
834                                 return null;
835                         }
836
837                 });
838
839                 /** Memoizer for the track derivatives. */
840                 private final Memoizer<Void> derivativesMemoizer = new Memoizer<Void>(new Callable<Void>() {
841
842                         @Override
843                         public Void call() throws Exception {
844                                 if (!hasValue("derivatives")) {
845                                         getValue("derivatives", Collection.class).set(getTrackDerivativesByTrack(getId()));
846                                 }
847                                 return null;
848                         }
849
850                 });
851
852                 /** Memoizer for the related tracks. */
853                 private final Memoizer<Void> relatedTracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
854
855                         @Override
856                         public Void call() throws Exception {
857                                 if (!hasValue("relatedTracks")) {
858                                         getValue("relatedTracks", Map.class).set(getRelatedTracksByTrack(getId()));
859                                 }
860                                 return null;
861                         }
862
863                 });
864
865                 /**
866                  * Creates a new track.
867                  *
868                  * @param id
869                  *            The ID of the track
870                  */
871                 public LazyTrack(String id) {
872                         super(id);
873                 }
874
875                 //
876                 // DEFAULTTRACK METHODS
877                 //
878
879                 /**
880                  * {@inheritDoc}
881                  */
882                 @Override
883                 public List<Artist> getArtists() {
884                         artistsMemoizer.get();
885                         return super.getArtists();
886                 }
887
888                 /**
889                  * {@inheritDoc}
890                  */
891                 @Override
892                 public Collection<Style> getStyles() {
893                         stylesMemoizer.get();
894                         return super.getStyles();
895                 }
896
897                 /**
898                  * {@inheritDoc}
899                  */
900                 @Override
901                 public List<Artist> getRemixArtists() {
902                         remixArtistsMemoizer.get();
903                         return super.getRemixArtists();
904                 }
905
906                 /**
907                  * {@inheritDoc}
908                  */
909                 @Override
910                 public Collection<TrackDerivative> getDerivatives() {
911                         derivativesMemoizer.get();
912                         return super.getDerivatives();
913                 }
914
915                 /**
916                  * {@inheritDoc}
917                  */
918                 @Override
919                 public Map<Relationship, Collection<Track>> getRelatedTracks() {
920                         relatedTracksMemoizer.get();
921                         return super.getRelatedTracks();
922                 }
923
924         }
925
926         /**
927          * {@link ObjectCreator} implementation that can create {@link Track}
928          * objects. This specific implementation creates {@link LazyTrack}
929          * instances.
930          *
931          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
932          */
933         private class TrackCreator implements ObjectCreator<Track> {
934
935                 /**
936                  * {@inheritDoc}
937                  */
938                 @Override
939                 public Track createObject(ResultSet resultSet) throws SQLException {
940                         return new LazyTrack(resultSet.getString("TRACKS.ID")).setName(resultSet.getString("TRACKS.NAME")).setRemix(resultSet.getString("TRACKS.REMIX"));
941                 }
942
943         }
944
945         /**
946          * {@link ObjectCreator} implementation that can create
947          * {@link TrackDerivative} objects.
948          *
949          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
950          */
951         private class TrackDerivativeCreator implements ObjectCreator<TrackDerivative> {
952
953                 /**
954                  * {@inheritDoc}
955                  */
956                 @Override
957                 public TrackDerivative createObject(ResultSet resultSet) throws SQLException {
958                         return new DefaultTrackDerivative(resultSet.getString("TRACK_DERIVATIVES.ID"));
959                 }
960
961         }
962
963         /**
964          * {@link ObjectCreator} implementation that can create {@link Style}
965          * objects.
966          *
967          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
968          */
969         private class StyleCreator implements ObjectCreator<Style> {
970
971                 /**
972                  * {@inheritDoc}
973                  */
974                 @Override
975                 public Style createObject(ResultSet resultSet) throws SQLException {
976                         return new DefaultStyle(resultSet.getString("STYLES.ID")).setName(resultSet.getString("STYLES.NAME"));
977                 }
978
979         }
980
981         /**
982          * {@link User} implementation that retrieves some attributes (such as
983          * {@link #getOpenIds()}) from the {@link DataManager} on demand.
984          *
985          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
986          */
987         private class LazyUser extends DefaultUser {
988
989                 /** Memoizer for a user’s OpenIDs. */
990                 private final Memoizer<Void> openIdMemoizer = new Memoizer<Void>(new Callable<Void>() {
991
992                         @Override
993                         public Void call() throws Exception {
994                                 if (!hasValue("openIds")) {
995                                         getValue("openIds", Collection.class).set(getOpenIdsByUser(getId()));
996                                 }
997                                 return null;
998                         }
999                 });
1000
1001                 /**
1002                  * Creates a new user.
1003                  *
1004                  * @param id
1005                  *            The ID of the user
1006                  */
1007                 public LazyUser(String id) {
1008                         super(id);
1009                 }
1010
1011                 /**
1012                  * {@inheritDoc}
1013                  */
1014                 @Override
1015                 public Collection<String> getOpenIds() {
1016                         openIdMemoizer.get();
1017                         return super.getOpenIds();
1018                 }
1019
1020         }
1021
1022         /**
1023          * {@link ObjectCreator} implementation that can create {@link User}
1024          * objects. This specific implementation creates {@link LazyUser} instances.
1025          *
1026          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1027          */
1028         private class UserCreator implements ObjectCreator<User> {
1029
1030                 /**
1031                  * {@inheritDoc}
1032                  */
1033                 @Override
1034                 public User createObject(ResultSet resultSet) throws SQLException {
1035                         return new LazyUser(resultSet.getString("USERS.ID")).setName(resultSet.getString("USERS.NAME")).setPasswordHash(resultSet.getString("USERS.PASSWORD")).setLevel(resultSet.getInt("USERS.LEVEL"));
1036                 }
1037
1038         }
1039
1040 }