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