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