Add related tracks to track interface.
[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.concurrent.Callable;
28
29 import net.pterodactylus.demoscenemusic.data.Track.Relationship;
30 import net.pterodactylus.util.collection.Memoizer;
31 import net.pterodactylus.util.database.Database;
32 import net.pterodactylus.util.database.DatabaseException;
33 import net.pterodactylus.util.database.Field;
34 import net.pterodactylus.util.database.Join;
35 import net.pterodactylus.util.database.Join.JoinType;
36 import net.pterodactylus.util.database.ObjectCreator;
37 import net.pterodactylus.util.database.OrderField;
38 import net.pterodactylus.util.database.Parameter.StringParameter;
39 import net.pterodactylus.util.database.Query;
40 import net.pterodactylus.util.database.Query.Type;
41 import net.pterodactylus.util.database.ResultProcessor;
42 import net.pterodactylus.util.database.ValueField;
43 import net.pterodactylus.util.database.ValueFieldWhereClause;
44
45 /**
46  * Interface between the database and the application.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class DataManager {
51
52         /** The artist object creator. */
53         @SuppressWarnings("synthetic-access")
54         private final ObjectCreator<Artist> artistCreator = new ArtistCreator();
55
56         /** The group object creator. */
57         @SuppressWarnings("synthetic-access")
58         private final ObjectCreator<Group> groupCreator = new GroupCreator();
59
60         /** The track object creator. */
61         @SuppressWarnings("synthetic-access")
62         private final ObjectCreator<Track> trackCreator = new TrackCreator();
63
64         /** The style object creator. */
65         @SuppressWarnings("synthetic-access")
66         private final ObjectCreator<Style> styleCreator = new StyleCreator();
67
68         /** The database. */
69         private final Database database;
70
71         /**
72          * Creates a new data manager.
73          *
74          * @param database
75          *            The database to operate on
76          */
77         public DataManager(Database database) {
78                 this.database = database;
79         }
80
81         /**
82          * Returns all artists.
83          *
84          * @return All artists
85          * @throws DatabaseException
86          *             if a database error occurs
87          */
88         public Collection<Artist> getAllArtists() throws DatabaseException {
89                 Query query = new Query(Type.SELECT, "ARTISTS");
90                 query.addField(new Field("ARTISTS.*"));
91                 return database.getMultiple(query, artistCreator);
92         }
93
94         /**
95          * Returns the artist with the given ID.
96          *
97          * @param id
98          *            The ID of the artist
99          * @return The artist with the given ID, or {@code null} if there is no
100          *         artist with the given ID
101          * @throws DatabaseException
102          *             if a database error occurs
103          */
104         public Artist getArtistById(String id) throws DatabaseException {
105                 Query query = new Query(Type.SELECT, "ARTISTS");
106                 query.addField(new Field("ARTISTS.*"));
107                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("ARTISTS.ID", new StringParameter(id))));
108                 return database.getSingle(query, artistCreator);
109         }
110
111         /**
112          * Returns all artists that belong to the group with the given ID.
113          *
114          * @param groupId
115          *            The ID of the group
116          * @return All artists belonging to the given group
117          * @throws DatabaseException
118          *             if a database error occurs
119          */
120         public Collection<Artist> getArtistsByGroup(String groupId) throws DatabaseException {
121                 Query query = new Query(Type.SELECT, "ARTISTS");
122                 query.addField(new Field("ARTISTS.*"));
123                 query.addJoin(new Join(JoinType.INNER, "GROUP_ARTISTS", new Field("ARTISTS.ID"), new Field("GROUP_ARTISTS.ARTIST")));
124                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUP_ARTISTS.GROUP_", new StringParameter(groupId))));
125                 return database.getMultiple(query, artistCreator);
126         }
127
128         /**
129          * Returns all artists involved in the track with the given ID.
130          *
131          * @param trackId
132          *            The ID of the track
133          * @return All artists involved in the track, in preferred order
134          * @throws DatabaseException
135          *             if a database error occurs
136          */
137         public List<Artist> getArtistsByTrack(String trackId) throws DatabaseException {
138                 Query query = new Query(Type.SELECT, "ARTISTS");
139                 query.addField(new Field("ARTISTS.*"));
140                 query.addJoin(new Join(JoinType.INNER, "TRACK_ARTISTS", new Field("TRACK_ARTISTS.ARTIST"), new Field("ARTISTS.ID")));
141                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_ARTISTS.TRACK", new StringParameter(trackId))));
142                 query.addOrderField(new OrderField(new Field("TRACK_ARTISTS.DISPLAY_ORDER")));
143                 return database.getMultiple(query, artistCreator);
144         }
145
146         /**
147          * Returns all remix artists involved in the track with the given ID.
148          *
149          * @param trackId
150          *            The ID of the track
151          * @return All remix artists involved in the track, in preferred order
152          * @throws DatabaseException
153          *             if a database error occurs
154          */
155         public List<Artist> getRemixArtistsByTrack(String trackId) throws DatabaseException {
156                 Query query = new Query(Type.SELECT, "ARTISTS");
157                 query.addField(new Field("ARTISTS.*"));
158                 query.addJoin(new Join(JoinType.INNER, "TRACK_REMIX_ARTISTS", new Field("TRACK_REMIX_ARTISTS.ARTIST"), new Field("ARTISTS.ID")));
159                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_REMIX_ARTISTS.TRACK", new StringParameter(trackId))));
160                 query.addOrderField(new OrderField(new Field("TRACK_REMIX_ARTISTS.DISPLAY_ORDER")));
161                 return database.getMultiple(query, artistCreator);
162         }
163
164         /**
165          * Returns all related tracks for the track with the given ID.
166          *
167          * @param trackId
168          *            The ID of the tracks
169          * @return A mapping from relationship to all tracks that match the relation
170          * @throws DatabaseException
171          *             if a database error occurs
172          */
173         public Map<Relationship, Collection<Track>> getRelatedTracksByTrack(String trackId) throws DatabaseException {
174                 Query query = new Query(Type.SELECT, "TRACKS");
175                 query.addField(new Field("TRACKS.*"));
176                 query.addField(new Field("TRACK_RELATIONS.*"));
177                 query.addJoin(new Join(JoinType.INNER, "TRACK_RELATIONS", new Field("TRACK_RELATIONS.TRACK"), new Field("TRACK_RELATIONS.RELATED_TRACK")));
178                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_RELATIONS.TRACK", new StringParameter(trackId))));
179                 final Map<Relationship, Collection<Track>> relatedTracks = new EnumMap<Relationship, Collection<Track>>(Relationship.class);
180                 database.process(query, new ResultProcessor() {
181
182                         @Override
183                         @SuppressWarnings("synthetic-access")
184                         public void processResult(ResultSet resultSet) throws SQLException {
185                                 Track track = trackCreator.createObject(resultSet);
186                                 Relationship relationship = Relationship.valueOf(resultSet.getString("TRACK_RELATIONS.RELATIONSHIP"));
187                                 if (!relatedTracks.containsKey(relationship)) {
188                                         relatedTracks.put(relationship, new HashSet<Track>());
189                                 }
190                                 relatedTracks.get(relationship).add(track);
191                         }
192                 });
193                 return relatedTracks;
194         }
195
196         /**
197          * Returns the track with the given ID.
198          *
199          * @param id
200          *            The ID of the track
201          * @return The track with the given ID, or {@code null} if there is no such
202          *         track
203          * @throws DatabaseException
204          *             if a database error occurs
205          */
206         public Track getTrackById(String id) throws DatabaseException {
207                 Query query = new Query(Type.SELECT, "TRACKS");
208                 query.addField(new Field("TRACKS.*"));
209                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACKS.ID", new StringParameter(id))));
210                 return database.getSingle(query, trackCreator);
211         }
212
213         /**
214          * Returns all tracks by the artist with the given ID.
215          *
216          * @param artistId
217          *            The ID of the artist
218          * @return All tracks by the given artist
219          * @throws DatabaseException
220          *             if a database error occurs
221          */
222         public Collection<Track> getTracksByArtist(String artistId) throws DatabaseException {
223                 Query query = new Query(Type.SELECT, "TRACKS");
224                 query.addField(new Field("TRACKS.*"));
225                 query.addJoin(new Join(JoinType.INNER, "TRACK_ARTISTS", new Field("TRACKS.ID"), new Field("TRACK_ARTISTS.TRACK")));
226                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_ARTISTS.ARTIST", new StringParameter(artistId))));
227                 return database.getMultiple(query, trackCreator);
228         }
229
230         /**
231          * Returns all groups the artist with the given ID belongs to.
232          *
233          * @param artistId
234          *            The ID of the artist
235          * @return All groups the artist belongs to
236          * @throws DatabaseException
237          *             if a database error occurs
238          */
239         public Collection<Group> getGroupsByArtist(String artistId) throws DatabaseException {
240                 Query query = new Query(Type.SELECT, "GROUPS");
241                 query.addField(new Field("GROUPS.*"));
242                 query.addJoin(new Join(JoinType.INNER, "GROUP_ARTISTS", new Field("GROUPS.ID"), new Field("GROUP_ARTISTS.GROUP_")));
243                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("GROUP_ARTISTS.ARTIST", new StringParameter(artistId))));
244                 return database.getMultiple(query, groupCreator);
245         }
246
247         /**
248          * Returns all styles for the track with the given ID.
249          *
250          * @param trackId
251          *            The ID of the track
252          * @return All styles for the given track
253          * @throws DatabaseException
254          *             if a database error occurs
255          */
256         public Collection<Style> getStylesByTrack(String trackId) throws DatabaseException {
257                 Query query = new Query(Type.SELECT, "STYLES");
258                 query.addField(new Field("STYLES.*"));
259                 query.addJoin(new Join(JoinType.INNER, "TRACK_STYLES", new Field("STYLES.ID"), new Field("TRACK_STYLES.STYLE")));
260                 query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_STYLES.TRACK", new StringParameter(trackId))));
261                 return database.getMultiple(query, styleCreator);
262         }
263
264         /**
265          * {@link Artist} implementation that retrieves some attributes (such as
266          * {@link #getGroups()}, and {@link #getTracks()}) from the
267          * {@link DataManager} on demand.
268          *
269          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
270          */
271         private class LazyArtist extends DefaultArtist {
272
273                 /** Memoizer for the tracks by this artist. */
274                 private final Memoizer<Void> tracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
275                         @Override
276                         public Void call() throws DatabaseException {
277                                 if (!hasValue("tracks")) {
278                                         getValue("tracks", Collection.class).set(getTracksByArtist(getId()));
279                                 }
280                                 return null;
281                         }
282                 });
283
284                 /** Memoizer for the groups of this artist. */
285                 private final Memoizer<Void> groupsMemoizer = new Memoizer<Void>(new Callable<Void>() {
286
287                         @Override
288                         public Void call() throws Exception {
289                                 if (!hasValue("groups")) {
290                                         getValue("groups", Collection.class).set(getGroupsByArtist(getId()));
291                                 }
292                                 return null;
293                         }
294
295                 });
296
297                 /**
298                  * Creates a new lazy artist.
299                  *
300                  * @param id
301                  *            The ID of the artist
302                  */
303                 public LazyArtist(String id) {
304                         super(id);
305                 }
306
307                 //
308                 // DEFAULTARTIST METHODS
309                 //
310
311                 /**
312                  * {@inheritDoc}
313                  */
314                 @Override
315                 public Collection<Group> getGroups() {
316                         groupsMemoizer.get();
317                         return super.getGroups();
318                 }
319
320                 /**
321                  * {@inheritDoc}
322                  */
323                 @Override
324                 public Collection<Track> getTracks() {
325                         tracksMemoizer.get();
326                         return super.getTracks();
327                 }
328
329         }
330
331         /**
332          * {@link ObjectCreator} implementation that can create {@link Artist}
333          * objects. This specific class actually creates {@link LazyArtist}
334          * instances.
335          *
336          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
337          */
338         private class ArtistCreator implements ObjectCreator<Artist> {
339
340                 /**
341                  * {@inheritDoc}
342                  */
343                 @Override
344                 public Artist createObject(ResultSet resultSet) throws SQLException {
345                         return new LazyArtist(resultSet.getString("ARTISTS.ID")).setName(resultSet.getString("ARTISTS.NAME"));
346                 }
347
348         }
349
350         /**
351          * {@link Group} implementation that retrieves some attributes (such as
352          * {@link #getArtists()}) from the {@link DataManager} on demand.
353          *
354          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
355          */
356         private class LazyGroup extends DefaultGroup {
357
358                 /** Memoizer for the artist. */
359                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
360
361                         @Override
362                         public Void call() throws Exception {
363                                 if (!hasValue("artists")) {
364                                         getValue("artists", Collection.class).set(getArtistsByGroup(getId()));
365                                 }
366                                 return null;
367                         }
368
369                 });
370
371                 /**
372                  * Creates a new lazy group.
373                  *
374                  * @param id
375                  *            The ID of the group
376                  */
377                 public LazyGroup(String id) {
378                         super(id);
379                 }
380
381                 //
382                 // DEFAULTGROUP METHODS
383                 //
384
385                 /**
386                  * {@inheritDoc}
387                  */
388                 @Override
389                 public Collection<Artist> getArtists() {
390                         artistsMemoizer.get();
391                         return super.getArtists();
392                 }
393
394         }
395
396         /**
397          * {@link ObjectCreator} implementation that can create {@link Group}
398          * objects. This specific implementation creates {@link LazyGroup}
399          * instances.
400          *
401          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
402          */
403         private class GroupCreator implements ObjectCreator<Group> {
404
405                 /**
406                  * {@inheritDoc}
407                  */
408                 @Override
409                 public Group createObject(ResultSet resultSet) throws SQLException {
410                         return new LazyGroup(resultSet.getString("GROUPS.ID")).setName(resultSet.getString("GROUPS.NAME")).setUrl(resultSet.getString("GROUPS.URL"));
411                 }
412
413         }
414
415         /**
416          * {@link Track} implementation that retrieves some attributes (such as
417          * {@link #getArtists()}, and {@link #getStyles()}) from the
418          * {@link DataManager} on demand.
419          *
420          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
421          */
422         private class LazyTrack extends DefaultTrack {
423
424                 /** Memoizer for the artists. */
425                 private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
426
427                         @Override
428                         public Void call() throws Exception {
429                                 if (!hasValue("artists")) {
430                                         getValue("artists", List.class).set(getArtistsByTrack(getId()));
431                                 }
432                                 return null;
433                         }
434
435                 });
436
437                 /** Memoizer for the styles. */
438                 private final Memoizer<Void> stylesMemoizer = new Memoizer<Void>(new Callable<Void>() {
439
440                         @Override
441                         public Void call() throws Exception {
442                                 if (!hasValue("styles")) {
443                                         getValue("styles", Collection.class).set(getStylesByTrack(getId()));
444                                 }
445                                 return null;
446                         }
447
448                 });
449
450                 /** Memoizer for the remix artists. */
451                 private final Memoizer<Void> remixArtistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
452
453                         @Override
454                         public Void call() throws Exception {
455                                 if (!hasValue("remixArtists")) {
456                                         getValue("remixArtists", List.class).set(getRemixArtistsByTrack(getId()));
457                                 }
458                                 return null;
459                         }
460
461                 });
462
463                 /** Memoizer for the related tracks. */
464                 private final Memoizer<Void> relatedTracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
465
466                         @Override
467                         public Void call() throws Exception {
468                                 if (!hasValue("relatedTracks")) {
469                                         getValue("relatedTracks", Map.class).set(getRelatedTracksByTrack(getId()));
470                                 }
471                                 return null;
472                         }
473                 });
474
475                 /**
476                  * Creates a new track.
477                  *
478                  * @param id
479                  *            The ID of the track
480                  */
481                 public LazyTrack(String id) {
482                         super(id);
483                 }
484
485                 //
486                 // DEFAULTTRACK METHODS
487                 //
488
489                 /**
490                  * {@inheritDoc}
491                  */
492                 @Override
493                 public List<Artist> getArtists() {
494                         artistsMemoizer.get();
495                         return super.getArtists();
496                 }
497
498                 /**
499                  * {@inheritDoc}
500                  */
501                 @Override
502                 public Collection<Style> getStyles() {
503                         stylesMemoizer.get();
504                         return super.getStyles();
505                 }
506
507                 /**
508                  * {@inheritDoc}
509                  */
510                 @Override
511                 public List<Artist> getRemixArtists() {
512                         remixArtistsMemoizer.get();
513                         return super.getRemixArtists();
514                 }
515
516                 /**
517                  * {@inheritDoc}
518                  */
519                 @Override
520                 public Map<Relationship, Collection<Track>> getRelatedTracks() {
521                         relatedTracksMemoizer.get();
522                         return super.getRelatedTracks();
523                 }
524
525         }
526
527         /**
528          * {@link ObjectCreator} implementation that can create {@link Track}
529          * objects. This specific implementation creates {@link LazyTrack}
530          * instances.
531          *
532          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
533          */
534         private class TrackCreator implements ObjectCreator<Track> {
535
536                 /**
537                  * {@inheritDoc}
538                  */
539                 @Override
540                 public Track createObject(ResultSet resultSet) throws SQLException {
541                         return new LazyTrack(resultSet.getString("TRACKS.ID")).setName(resultSet.getString("TRACKS.NAME")).setRemix(resultSet.getString("TRACKS.REMIX"));
542                 }
543
544         }
545
546         /**
547          * {@link ObjectCreator} implementation that can create {@link Style}
548          * objects.
549          *
550          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
551          */
552         private class StyleCreator implements ObjectCreator<Style> {
553
554                 /**
555                  * {@inheritDoc}
556                  */
557                 @Override
558                 public Style createObject(ResultSet resultSet) throws SQLException {
559                         return new DefaultStyle(resultSet.getString("STYLES.ID")).setName(resultSet.getString("STYLES.NAME"));
560                 }
561
562         }
563
564 }