Add login page.
[demoscenemusic.git] / src / main / java / net / pterodactylus / demoscenemusic / data / DataManager.java
index 9ec6d73..60b8318 100644 (file)
@@ -20,9 +20,13 @@ package net.pterodactylus.demoscenemusic.data;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.concurrent.Callable;
 
+import net.pterodactylus.demoscenemusic.data.Track.Relationship;
 import net.pterodactylus.util.collection.Memoizer;
 import net.pterodactylus.util.database.Database;
 import net.pterodactylus.util.database.DatabaseException;
@@ -30,36 +34,78 @@ import net.pterodactylus.util.database.Field;
 import net.pterodactylus.util.database.Join;
 import net.pterodactylus.util.database.Join.JoinType;
 import net.pterodactylus.util.database.ObjectCreator;
+import net.pterodactylus.util.database.ObjectCreator.StringCreator;
 import net.pterodactylus.util.database.OrderField;
 import net.pterodactylus.util.database.Parameter.StringParameter;
 import net.pterodactylus.util.database.Query;
 import net.pterodactylus.util.database.Query.Type;
+import net.pterodactylus.util.database.ResultProcessor;
 import net.pterodactylus.util.database.ValueField;
 import net.pterodactylus.util.database.ValueFieldWhereClause;
 
 /**
- * TODO
+ * Interface between the database and the application.
  *
  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
  */
 public class DataManager {
 
+       /** The artist object creator. */
+       @SuppressWarnings("synthetic-access")
        private final ObjectCreator<Artist> artistCreator = new ArtistCreator();
+
+       /** The group object creator. */
+       @SuppressWarnings("synthetic-access")
        private final ObjectCreator<Group> groupCreator = new GroupCreator();
+
+       /** The track object creator. */
+       @SuppressWarnings("synthetic-access")
        private final ObjectCreator<Track> trackCreator = new TrackCreator();
 
+       /** The style object creator. */
+       @SuppressWarnings("synthetic-access")
+       private final ObjectCreator<Style> styleCreator = new StyleCreator();
+
+       /** The {@link User} object creator. */
+       @SuppressWarnings("synthetic-access")
+       private final ObjectCreator<User> userCreator = new UserCreator();
+
+       /** The database. */
        private final Database database;
 
+       /**
+        * Creates a new data manager.
+        *
+        * @param database
+        *            The database to operate on
+        */
        public DataManager(Database database) {
                this.database = database;
        }
 
+       /**
+        * Returns all artists.
+        *
+        * @return All artists
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
        public Collection<Artist> getAllArtists() throws DatabaseException {
                Query query = new Query(Type.SELECT, "ARTISTS");
                query.addField(new Field("ARTISTS.*"));
                return database.getMultiple(query, artistCreator);
        }
 
+       /**
+        * Returns the artist with the given ID.
+        *
+        * @param id
+        *            The ID of the artist
+        * @return The artist with the given ID, or {@code null} if there is no
+        *         artist with the given ID
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
        public Artist getArtistById(String id) throws DatabaseException {
                Query query = new Query(Type.SELECT, "ARTISTS");
                query.addField(new Field("ARTISTS.*"));
@@ -67,6 +113,15 @@ public class DataManager {
                return database.getSingle(query, artistCreator);
        }
 
+       /**
+        * Returns all artists that belong to the group with the given ID.
+        *
+        * @param groupId
+        *            The ID of the group
+        * @return All artists belonging to the given group
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
        public Collection<Artist> getArtistsByGroup(String groupId) throws DatabaseException {
                Query query = new Query(Type.SELECT, "ARTISTS");
                query.addField(new Field("ARTISTS.*"));
@@ -75,6 +130,15 @@ public class DataManager {
                return database.getMultiple(query, artistCreator);
        }
 
+       /**
+        * Returns all artists involved in the track with the given ID.
+        *
+        * @param trackId
+        *            The ID of the track
+        * @return All artists involved in the track, in preferred order
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
        public List<Artist> getArtistsByTrack(String trackId) throws DatabaseException {
                Query query = new Query(Type.SELECT, "ARTISTS");
                query.addField(new Field("ARTISTS.*"));
@@ -84,13 +148,82 @@ public class DataManager {
                return database.getMultiple(query, artistCreator);
        }
 
-       public Track trackById(String id) throws DatabaseException {
+       /**
+        * Returns all remix artists involved in the track with the given ID.
+        *
+        * @param trackId
+        *            The ID of the track
+        * @return All remix artists involved in the track, in preferred order
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
+       public List<Artist> getRemixArtistsByTrack(String trackId) throws DatabaseException {
+               Query query = new Query(Type.SELECT, "ARTISTS");
+               query.addField(new Field("ARTISTS.*"));
+               query.addJoin(new Join(JoinType.INNER, "TRACK_REMIX_ARTISTS", new Field("TRACK_REMIX_ARTISTS.ARTIST"), new Field("ARTISTS.ID")));
+               query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_REMIX_ARTISTS.TRACK", new StringParameter(trackId))));
+               query.addOrderField(new OrderField(new Field("TRACK_REMIX_ARTISTS.DISPLAY_ORDER")));
+               return database.getMultiple(query, artistCreator);
+       }
+
+       /**
+        * Returns all related tracks for the track with the given ID.
+        *
+        * @param trackId
+        *            The ID of the tracks
+        * @return A mapping from relationship to all tracks that match the relation
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
+       public Map<Relationship, Collection<Track>> getRelatedTracksByTrack(String trackId) throws DatabaseException {
+               Query query = new Query(Type.SELECT, "TRACKS");
+               query.addField(new Field("TRACKS.*"));
+               query.addField(new Field("TRACK_RELATIONS.*"));
+               query.addJoin(new Join(JoinType.INNER, "TRACK_RELATIONS", new Field("TRACK_RELATIONS.TRACK"), new Field("TRACK_RELATIONS.RELATED_TRACK")));
+               query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_RELATIONS.TRACK", new StringParameter(trackId))));
+               final Map<Relationship, Collection<Track>> relatedTracks = new EnumMap<Relationship, Collection<Track>>(Relationship.class);
+               database.process(query, new ResultProcessor() {
+
+                       @Override
+                       @SuppressWarnings("synthetic-access")
+                       public void processResult(ResultSet resultSet) throws SQLException {
+                               Track track = trackCreator.createObject(resultSet);
+                               Relationship relationship = Relationship.valueOf(resultSet.getString("TRACK_RELATIONS.RELATIONSHIP"));
+                               if (!relatedTracks.containsKey(relationship)) {
+                                       relatedTracks.put(relationship, new HashSet<Track>());
+                               }
+                               relatedTracks.get(relationship).add(track);
+                       }
+               });
+               return relatedTracks;
+       }
+
+       /**
+        * Returns the track with the given ID.
+        *
+        * @param id
+        *            The ID of the track
+        * @return The track with the given ID, or {@code null} if there is no such
+        *         track
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
+       public Track getTrackById(String id) throws DatabaseException {
                Query query = new Query(Type.SELECT, "TRACKS");
                query.addField(new Field("TRACKS.*"));
                query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACKS.ID", new StringParameter(id))));
                return database.getSingle(query, trackCreator);
        }
 
+       /**
+        * Returns all tracks by the artist with the given ID.
+        *
+        * @param artistId
+        *            The ID of the artist
+        * @return All tracks by the given artist
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
        public Collection<Track> getTracksByArtist(String artistId) throws DatabaseException {
                Query query = new Query(Type.SELECT, "TRACKS");
                query.addField(new Field("TRACKS.*"));
@@ -99,6 +232,15 @@ public class DataManager {
                return database.getMultiple(query, trackCreator);
        }
 
+       /**
+        * Returns all groups the artist with the given ID belongs to.
+        *
+        * @param artistId
+        *            The ID of the artist
+        * @return All groups the artist belongs to
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
        public Collection<Group> getGroupsByArtist(String artistId) throws DatabaseException {
                Query query = new Query(Type.SELECT, "GROUPS");
                query.addField(new Field("GROUPS.*"));
@@ -107,49 +249,147 @@ public class DataManager {
                return database.getMultiple(query, groupCreator);
        }
 
+       /**
+        * Returns all styles for the track with the given ID.
+        *
+        * @param trackId
+        *            The ID of the track
+        * @return All styles for the given track
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
+       public Collection<Style> getStylesByTrack(String trackId) throws DatabaseException {
+               Query query = new Query(Type.SELECT, "STYLES");
+               query.addField(new Field("STYLES.*"));
+               query.addJoin(new Join(JoinType.INNER, "TRACK_STYLES", new Field("STYLES.ID"), new Field("TRACK_STYLES.STYLE")));
+               query.addWhereClause(new ValueFieldWhereClause(new ValueField("TRACK_STYLES.TRACK", new StringParameter(trackId))));
+               return database.getMultiple(query, styleCreator);
+       }
+
+       /**
+        * Returns the user with the given name.
+        *
+        * @param username
+        *            The name of the user
+        * @return The user, or {@code null} if the user does not exist
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
+       public User getUserByName(String username) throws DatabaseException {
+               Query query = new Query(Type.SELECT, "USERS");
+               query.addField(new Field("USERS.*"));
+               query.addWhereClause(new ValueFieldWhereClause(new ValueField("USERS.NAME", new StringParameter(username))));
+               return database.getSingle(query, userCreator);
+       }
+
+       /**
+        * Returns the user connected with the given OpenID.
+        *
+        * @param openId
+        *            The OpenID to find the user for
+        * @return The user connected with the given OpenID, or {@code null} if
+        *         there is no such user
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
+       public User getUserByOpenId(String openId) throws DatabaseException {
+               Query query = new Query(Type.SELECT, "USERS");
+               query.addField(new Field("USERS.*"));
+               query.addJoin(new Join(JoinType.INNER, "USER_OPENIDS", new Field("USER_OPENIDS.USER"), new Field("USERS.ID")));
+               query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.OPENID", new StringParameter(openId))));
+               return database.getSingle(query, userCreator);
+       }
+
+       /**
+        * Returns all OpenIDs connected with the user with the given ID.
+        *
+        * @param userId
+        *            The ID of the user
+        * @return All OpenIDs connected with the given user
+        * @throws DatabaseException
+        *             if a database error occurs
+        */
+       public Collection<String> getOpenIdsByUser(String userId) throws DatabaseException {
+               Query query = new Query(Type.SELECT, "USER_OPENIDS");
+               query.addField(new Field("USER_OPENIDS.*"));
+               query.addWhereClause(new ValueFieldWhereClause(new ValueField("USER_OPENIDS.USER", new StringParameter(userId))));
+               return database.getMultiple(query, new StringCreator("USER_OPENIDS.OPENID"));
+       }
+
+       /**
+        * {@link Artist} implementation that retrieves some attributes (such as
+        * {@link #getGroups()}, and {@link #getTracks()}) from the
+        * {@link DataManager} on demand.
+        *
+        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+        */
        private class LazyArtist extends DefaultArtist {
 
+               /** Memoizer for the tracks by this artist. */
                private final Memoizer<Void> tracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
+                       @Override
                        public Void call() throws DatabaseException {
                                if (!hasValue("tracks")) {
-                                       value("tracks", Collection.class).set(getTracksByArtist(id()));
+                                       getValue("tracks", Collection.class).set(getTracksByArtist(getId()));
                                }
                                return null;
                        }
                });
 
+               /** Memoizer for the groups of this artist. */
                private final Memoizer<Void> groupsMemoizer = new Memoizer<Void>(new Callable<Void>() {
 
                        @Override
                        public Void call() throws Exception {
                                if (!hasValue("groups")) {
-                                       value("groups", Collection.class).set(getGroupsByArtist(id()));
+                                       getValue("groups", Collection.class).set(getGroupsByArtist(getId()));
                                }
                                return null;
                        }
 
                });
 
+               /**
+                * Creates a new lazy artist.
+                *
+                * @param id
+                *            The ID of the artist
+                */
                public LazyArtist(String id) {
                        super(id);
                }
 
+               //
+               // DEFAULTARTIST METHODS
+               //
+
                /**
                 * {@inheritDoc}
                 */
                @Override
-               public Collection<Group> groups() {
+               public Collection<Group> getGroups() {
                        groupsMemoizer.get();
-                       return super.groups();
+                       return super.getGroups();
                }
 
-               public Collection<Track> tracks() {
+               /**
+                * {@inheritDoc}
+                */
+               @Override
+               public Collection<Track> getTracks() {
                        tracksMemoizer.get();
-                       return super.tracks();
+                       return super.getTracks();
                }
 
        }
 
+       /**
+        * {@link ObjectCreator} implementation that can create {@link Artist}
+        * objects. This specific class actually creates {@link LazyArtist}
+        * instances.
+        *
+        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+        */
        private class ArtistCreator implements ObjectCreator<Artist> {
 
                /**
@@ -157,40 +397,64 @@ public class DataManager {
                 */
                @Override
                public Artist createObject(ResultSet resultSet) throws SQLException {
-                       return new LazyArtist(resultSet.getString("ARTISTS.ID")).name(resultSet.getString("ARTISTS.NAME"));
+                       return new LazyArtist(resultSet.getString("ARTISTS.ID")).setName(resultSet.getString("ARTISTS.NAME"));
                }
 
        }
 
+       /**
+        * {@link Group} implementation that retrieves some attributes (such as
+        * {@link #getArtists()}) from the {@link DataManager} on demand.
+        *
+        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+        */
        private class LazyGroup extends DefaultGroup {
 
+               /** Memoizer for the artist. */
                private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
 
                        @Override
                        public Void call() throws Exception {
                                if (!hasValue("artists")) {
-                                       value("artists", Collection.class).set(getArtistsByGroup(id()));
+                                       getValue("artists", Collection.class).set(getArtistsByGroup(getId()));
                                }
                                return null;
                        }
 
                });
 
+               /**
+                * Creates a new lazy group.
+                *
+                * @param id
+                *            The ID of the group
+                */
                public LazyGroup(String id) {
                        super(id);
                }
 
+               //
+               // DEFAULTGROUP METHODS
+               //
+
                /**
                 * {@inheritDoc}
                 */
                @Override
-               public Collection<Artist> artists() {
+               public Collection<Artist> getArtists() {
                        artistsMemoizer.get();
-                       return super.artists();
+                       return super.getArtists();
                }
 
        }
 
+       /**
+        * {@link ObjectCreator} implementation that can create {@link Group}
+        * objects. This specific implementation creates {@link LazyGroup}
+        * instances.
+        *
+        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+        */
        private class GroupCreator implements ObjectCreator<Group> {
 
                /**
@@ -198,52 +462,130 @@ public class DataManager {
                 */
                @Override
                public Group createObject(ResultSet resultSet) throws SQLException {
-                       return new LazyGroup(resultSet.getString("GROUPS.ID")).name(resultSet.getString("GROUPS.NAME")).url(resultSet.getString("GROUPS.URL"));
+                       return new LazyGroup(resultSet.getString("GROUPS.ID")).setName(resultSet.getString("GROUPS.NAME")).setUrl(resultSet.getString("GROUPS.URL"));
                }
 
        }
 
+       /**
+        * {@link Track} implementation that retrieves some attributes (such as
+        * {@link #getArtists()}, and {@link #getStyles()}) from the
+        * {@link DataManager} on demand.
+        *
+        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+        */
        private class LazyTrack extends DefaultTrack {
 
+               /** Memoizer for the artists. */
                private final Memoizer<Void> artistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
 
                        @Override
                        public Void call() throws Exception {
                                if (!hasValue("artists")) {
-                                       value("artists", List.class).set(getArtistsByTrack(id()));
+                                       getValue("artists", List.class).set(getArtistsByTrack(getId()));
+                               }
+                               return null;
+                       }
+
+               });
+
+               /** Memoizer for the styles. */
+               private final Memoizer<Void> stylesMemoizer = new Memoizer<Void>(new Callable<Void>() {
+
+                       @Override
+                       public Void call() throws Exception {
+                               if (!hasValue("styles")) {
+                                       getValue("styles", Collection.class).set(getStylesByTrack(getId()));
                                }
                                return null;
                        }
 
                });
 
+               /** Memoizer for the remix artists. */
+               private final Memoizer<Void> remixArtistsMemoizer = new Memoizer<Void>(new Callable<Void>() {
+
+                       @Override
+                       public Void call() throws Exception {
+                               if (!hasValue("remixArtists")) {
+                                       getValue("remixArtists", List.class).set(getRemixArtistsByTrack(getId()));
+                               }
+                               return null;
+                       }
+
+               });
+
+               /** Memoizer for the related tracks. */
+               private final Memoizer<Void> relatedTracksMemoizer = new Memoizer<Void>(new Callable<Void>() {
+
+                       @Override
+                       public Void call() throws Exception {
+                               if (!hasValue("relatedTracks")) {
+                                       getValue("relatedTracks", Map.class).set(getRelatedTracksByTrack(getId()));
+                               }
+                               return null;
+                       }
+               });
+
                /**
+                * Creates a new track.
+                *
                 * @param id
+                *            The ID of the track
                 */
                public LazyTrack(String id) {
                        super(id);
                }
 
+               //
+               // DEFAULTTRACK METHODS
+               //
+
                /**
                 * {@inheritDoc}
                 */
                @Override
-               public List<Artist> artists() {
+               public List<Artist> getArtists() {
                        artistsMemoizer.get();
-                       return super.artists();
+                       return super.getArtists();
+               }
+
+               /**
+                * {@inheritDoc}
+                */
+               @Override
+               public Collection<Style> getStyles() {
+                       stylesMemoizer.get();
+                       return super.getStyles();
+               }
+
+               /**
+                * {@inheritDoc}
+                */
+               @Override
+               public List<Artist> getRemixArtists() {
+                       remixArtistsMemoizer.get();
+                       return super.getRemixArtists();
                }
 
                /**
                 * {@inheritDoc}
                 */
                @Override
-               public Collection<Style> styles() {
-                       // TODO Auto-generated method stub
-                       return super.styles();
+               public Map<Relationship, Collection<Track>> getRelatedTracks() {
+                       relatedTracksMemoizer.get();
+                       return super.getRelatedTracks();
                }
 
        }
 
+       /**
+        * {@link ObjectCreator} implementation that can create {@link Track}
+        * objects. This specific implementation creates {@link LazyTrack}
+        * instances.
+        *
+        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+        */
        private class TrackCreator implements ObjectCreator<Track> {
 
                /**
@@ -251,7 +593,84 @@ public class DataManager {
                 */
                @Override
                public Track createObject(ResultSet resultSet) throws SQLException {
-                       return new LazyTrack(resultSet.getString("TRACKS.ID")).name(resultSet.getString("TRACKS.NAME"));
+                       return new LazyTrack(resultSet.getString("TRACKS.ID")).setName(resultSet.getString("TRACKS.NAME")).setRemix(resultSet.getString("TRACKS.REMIX"));
+               }
+
+       }
+
+       /**
+        * {@link ObjectCreator} implementation that can create {@link Style}
+        * objects.
+        *
+        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+        */
+       private class StyleCreator implements ObjectCreator<Style> {
+
+               /**
+                * {@inheritDoc}
+                */
+               @Override
+               public Style createObject(ResultSet resultSet) throws SQLException {
+                       return new DefaultStyle(resultSet.getString("STYLES.ID")).setName(resultSet.getString("STYLES.NAME"));
+               }
+
+       }
+
+       /**
+        * {@link User} implementation that retrieves some attributes (such as
+        * {@link #getOpenIds()}) from the {@link DataManager} on demand.
+        *
+        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+        */
+       private class LazyUser extends DefaultUser {
+
+               /** Memoizer for a user’s OpenIDs. */
+               private final Memoizer<Void> openIdMemoizer = new Memoizer<Void>(new Callable<Void>() {
+
+                       @Override
+                       public Void call() throws Exception {
+                               if (!hasValue("openIds")) {
+                                       getValue("openIds", Collection.class).set(getOpenIdsByUser(getId()));
+                               }
+                               return null;
+                       }
+               });
+
+               /**
+                * Creates a new user.
+                *
+                * @param id
+                *            The ID of the user
+                */
+               public LazyUser(String id) {
+                       super(id);
+               }
+
+               /**
+                * {@inheritDoc}
+                */
+               @Override
+               public Collection<String> getOpenIds() {
+                       openIdMemoizer.get();
+                       return super.getOpenIds();
+               }
+
+       }
+
+       /**
+        * {@link ObjectCreator} implementation that can create {@link User}
+        * objects. This specific implementation creates {@link LazyUser} instances.
+        *
+        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+        */
+       private class UserCreator implements ObjectCreator<User> {
+
+               /**
+                * {@inheritDoc}
+                */
+               @Override
+               public User createObject(ResultSet resultSet) throws SQLException {
+                       return new LazyUser(resultSet.getString("USERS.ID")).setName(resultSet.getString("USERS.NAME")).setPasswordHash(resultSet.getString("USERS.PASSWORD")).setLevel(resultSet.getInt("USERS.LEVEL"));
                }
 
        }