Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Playlist extends BaseEntity {
- private String name;
- private String description;
- private boolean isPublic;
- private int ownerId;
- public Playlist() {
- }
- public Playlist(String name, String description, boolean isPublic) {
- this.name = name;
- this.description = description;
- this.isPublic = isPublic;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public boolean isPublic() {
- return isPublic;
- }
- public void setPublic(boolean aPublic) {
- isPublic = aPublic;
- }
- public int getOwnerId() {
- return ownerId;
- }
- public void setOwnerId(int ownerId) {
- this.ownerId = ownerId;
- }
- @Override
- public String toString() {
- return "Playlist[" + getId() + "] - " + name + " Description - " + description;
- }
- public static enum COLUMNS {
- NAME("name"),
- DESCRIPTION("description"),
- IS_PUBLIC("is_public"),
- OWNER_ID("owner_id");
- private String value;
- COLUMNS(String value) {
- this.value = value;
- }
- public String getValue() {
- return value;
- }
- }
- }
- public class Song extends BaseEntity{
- private String name;
- private String artistName;
- private String year;
- public Song() {
- }
- public Song(String name, String artistName, String year) {
- this.name = name;
- this.artistName = artistName;
- this.year = year;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getArtistName() {
- return artistName;
- }
- public void setArtistName(String artistName) {
- this.artistName = artistName;
- }
- public String getYear() {
- return year;
- }
- public void setYear(String year) {
- this.year = year;
- }
- @Override
- public String toString() {
- return "Song[" + getId() + "] - " + name + " produced by " + artistName + " in " + year;
- }
- public static enum COLUMNS {
- NAME("name"),
- AUTHOR("author"),
- YEAR("year");
- private String value;
- COLUMNS(String value) {
- this.value = value;
- }
- public String getValue() {
- return value;
- }
- }
- }
- public class User extends BaseEntity{
- private String email;
- private String password;
- private String displayName;
- private boolean isAdministrator;
- public User() {
- }
- public User(String email, String password, String displayName, boolean isAdministrator) {
- this.email = email;
- this.password = password;
- this.displayName = displayName;
- this.isAdministrator = isAdministrator;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getDisplayName() {
- return displayName;
- }
- public void setDisplayName(String displayName) {
- this.displayName = displayName;
- }
- public boolean isAdministrator() {
- return isAdministrator;
- }
- public void setAdministrator(boolean administrator) {
- isAdministrator = administrator;
- }
- public static enum COLUMNS {
- EMAIL("email"),
- PASSWORD("password"),
- DISPLAY_NAME("display_name"),
- IS_ADMINISTRATOR("is_administrator");
- private String value;
- COLUMNS(String value) {
- this.value = value;
- }
- public String getValue() {
- return value;
- }
- }
- }
- // До тук са ентититата
- import com.emiltsonev.dao.BaseDao;
- import com.emiltsonev.entities.BaseEntity;
- import com.emiltsonev.entities.Playlist;
- import com.emiltsonev.entities.User;
- import java.io.IOException;
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.sql.*;
- import java.util.*;
- public class BaseDaoDbImpl<T extends BaseEntity> implements BaseDao<T> {
- private final static String CONNECTION_STRING = "jdbc:mysql://localhost/black_sound?useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
- private final Connection conn;
- private Class<T> entityClass;
- private String tableName;
- public BaseDaoDbImpl(Class<T> entityClass, String tableName) throws ClassNotFoundException, SQLException {
- this.entityClass = entityClass;
- this.tableName = tableName;
- Class.forName("com.mysql.cj.jdbc.Driver");
- conn = DriverManager.getConnection(CONNECTION_STRING, "emil", "emil");
- }
- public Connection getConn() {
- return conn;
- }
- public Class<T> getEntityClass() {
- return entityClass;
- }
- public String getTableName() {
- return tableName;
- }
- public static void main(String[] args) throws SQLException, ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException, IOException, NoSuchMethodException, InvocationTargetException {
- BaseDaoDbImpl<Playlist> songBaseDao = new BaseDaoDbImpl<>(Playlist.class, "playlists");
- BaseDaoDbImpl<User> userBaseDao = new BaseDaoDbImpl<>(User.class, "users");
- BaseDaoDbImpl<Playlist> playlistBaseDao = new BaseDaoDbImpl<>(Playlist.class, "playlists");
- }
- @Override
- public void update(int id) throws IOException, IllegalAccessException, NoSuchFieldException, InstantiationException, SQLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
- T entity = get(id);
- if(entity != null) {
- StringBuilder updateStatementBuilder = new StringBuilder("update " + tableName + " set ");
- Field[] fields = entityClass.getDeclaredFields();
- Scanner scanner = new Scanner(System.in);
- Class<?> enumClass = Class.forName(entityClass.getName() + "$COLUMNS");
- Method getValue = enumClass.getDeclaredMethod("getValue");
- Map<String, String> fieldsToColumnNames = new LinkedHashMap<>();
- Object[] columnNames = enumClass.getEnumConstants();
- for(int i = 0; i < fields.length; i++) {
- fields[i].setAccessible(true);
- fieldsToColumnNames.put(fields[i].getName(), (String) getValue.invoke(columnNames[i]));
- }
- String choice;
- for(Field field : fields) {
- field.setAccessible(true);
- System.out.println("Would you like to change the value of " + field.getName() + " [y/Y] to change it.");
- System.out.print("Please enter your choice: ");
- choice = scanner.nextLine();
- String newValue = null;
- if(choice.equals("Y") || choice.equals("y")) {
- if(field.getType() == boolean.class) {
- System.out.print("Enter [y/Y] for true and anything else for false: ");
- newValue = scanner.nextLine();
- if(newValue.equals("Y") || newValue.equals("y")) {
- field.set(entity, 1);
- } else {
- field.set(entity, 0);
- }
- } else {
- System.out.print("Enter value for: " + field.getName() + ": ");
- newValue = scanner.nextLine();
- field.set(entity, newValue);
- }
- if(field.getType() == String.class) {
- updateStatementBuilder.append(fieldsToColumnNames.get(field.getName()) + " = " + "'" + newValue + "'" + ", ");
- } else {
- updateStatementBuilder.append(fieldsToColumnNames.get(field.getName()) + " = " + newValue + ", ");
- }
- }
- }
- updateStatementBuilder.replace(updateStatementBuilder.length() - 2, updateStatementBuilder.length(), " where id=" + id);
- System.out.println(updateStatementBuilder.toString());
- Statement updateStatement = conn.createStatement();
- updateStatement.executeUpdate(updateStatementBuilder.toString());
- } else {
- System.out.println("No " + entityClass.getSimpleName() + " to be updated");
- }
- }
- @Override
- public void save(T entity) throws IOException, IllegalAccessException, NoSuchFieldException, InstantiationException, SQLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
- StringBuilder statementBuilder = new StringBuilder("insert into " + tableName + " (");
- Field[] fields = entityClass.getDeclaredFields();
- Class<?> enumClass = Class.forName(entityClass.getName() + "$COLUMNS");
- Method getValue = enumClass.getDeclaredMethod("getValue");
- for(Object object : enumClass.getEnumConstants()) {
- String val = (String) getValue.invoke(object);
- System.out.println(val);
- statementBuilder.append(val + ", ");
- }
- statementBuilder.replace(statementBuilder.length() - 2, statementBuilder.length(), "");
- statementBuilder.append(") values(");
- for(Field field : fields) {
- field.setAccessible(true);
- if(field.getType() == String.class) {
- statementBuilder.append("'" + field.get(entity) + "'" + ", ");
- continue;
- }
- if(field.getType() == boolean.class) {
- statementBuilder.append((boolean)field.get(entity)? 1 + ", " : 0 + ", ");
- continue;
- }
- statementBuilder.append(field.get(entity) + ", ");
- }
- statementBuilder.replace(statementBuilder.length() - 2, statementBuilder.length(), ")");
- System.out.println(statementBuilder.toString());
- Statement statement = null;
- try {
- statement = conn.createStatement();
- statement.executeUpdate(statementBuilder.toString(), Statement.RETURN_GENERATED_KEYS);
- ResultSet result = statement.getGeneratedKeys();
- result.next();
- System.out.println(result.getInt(1));
- entity.setId(result.getInt(1));
- } finally {
- if(statement != null) {
- statement.close();
- }
- }
- }
- @Override
- public void delete(int id) throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException, SQLException {
- T entity = get(id);
- if(entity != null) {
- StringBuilder statementBuilder = new StringBuilder("delete from " + tableName + " where id=" + entity.getId());
- try (Statement statement = conn.createStatement()) {
- statement.executeUpdate(statementBuilder.toString());
- System.out.println("Deletion from " + tableName + " successful");
- }
- } else {
- System.out.println("No " + entityClass.getSimpleName() + " to be deleted with id: " + id);
- }
- }
- @Override
- public T get(int id) throws NoSuchFieldException, InstantiationException, IllegalAccessException, IOException, SQLException {
- StringBuilder statementBuilder = new StringBuilder("select * from " + tableName + " where id=" + id);
- Field[] fields = entityClass.getDeclaredFields();
- int i = 2;
- try (Statement statement = conn.createStatement();
- ResultSet results = statement.executeQuery(statementBuilder.toString())) {
- if(!results.next()) {
- return null;
- }
- T entity = entityClass.newInstance();
- entity.setId(results.getInt("id"));
- while (results.next()) {
- for(Field field : fields) {
- field.setAccessible(true);
- if(field.getType() == boolean.class) {
- field.set(entity, results.getByte(i) == 1);
- i++;
- continue;
- }
- if(field.getType() == int.class) {
- field.set(entity, results.getInt(i));
- i++;
- continue;
- }
- field.set(entity, results.getString(i));
- i++;
- }
- i = 2;
- }
- return entity;
- }
- }
- @Override
- public List<T> getAll() throws IOException, IllegalAccessException, InstantiationException, NoSuchFieldException, SQLException {
- List<T> entities = new LinkedList<>();
- StringBuilder statementBuilder = new StringBuilder("select * from " + tableName);
- Field[] fields = entityClass.getDeclaredFields();
- try (Statement statement = conn.createStatement();
- ResultSet results = statement.executeQuery(statementBuilder.toString())) {
- int i = 2;
- while(results.next()) {
- T entity = entityClass.newInstance();
- entity.setId(results.getInt("id"));
- for(Field field : fields) {
- field.setAccessible(true);
- if(field.getType() == boolean.class) {
- field.set(entity, results.getByte(i) == 1);
- i++;
- continue;
- }
- if(field.getType() == int.class) {
- field.set(entity, results.getInt(i));
- i++;
- continue;
- }
- field.set(entity, results.getString(i));
- i++;
- }
- entities.add(entity);
- i = 2;
- }
- }
- return entities;
- }
- }
- import com.emiltsonev.entities.Playlist;
- import com.emiltsonev.entities.Song;
- import com.emiltsonev.util.services.AuthenticationService;
- import java.io.IOException;
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.*;
- public class PlaylistDaoDbImpl extends BaseDaoDbImpl<Playlist> {
- private PlaylistSongDaoDbImpl playlistSongDao = new PlaylistSongDaoDbImpl();
- public PlaylistDaoDbImpl(Class<Playlist> entityClass, String tableName) throws ClassNotFoundException, SQLException {
- super(entityClass, tableName);
- }
- @Override
- public void save(Playlist entity) throws IOException, IllegalAccessException, NoSuchFieldException, InstantiationException, SQLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
- entity.setOwnerId(AuthenticationService.instance().getUser().getId());
- super.save(entity);
- }
- public void addSongToPlaylist(int playlistId, int songId) throws SQLException {
- playlistSongDao.insert(playlistId, songId);
- }
- public List<Playlist> getAll(int id) throws SQLException {
- List<Playlist> playlists = new LinkedList<>();
- try(Statement statement = getConn().createStatement();
- ResultSet results = statement.executeQuery("select playlists.id, playlists.name, playlists.description, playlists.is_public, playlists.owner_id from playlists where playlists.owner_id = " + id)) {
- while(results.next()) {
- Playlist playlist = new Playlist();
- playlist.setId(results.getInt(1));
- playlist.setName(results.getString(2));
- playlist.setDescription(results.getString(3));
- playlist.setPublic(results.getInt(3) == 1);
- playlist.setOwnerId(results.getInt(4));
- playlists.add(playlist);
- }
- }
- return playlists;
- }
- public List<Song> getSongsByPlaylistId(int playlistId) throws SQLException {
- return playlistSongDao.getSongsByPlaylistId(playlistId);
- }
- @Override
- public void update(int id) throws IOException, IllegalAccessException, NoSuchFieldException, InstantiationException, SQLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
- Playlist entity = get(id);
- if(entity != null) {
- StringBuilder updateStatementBuilder = new StringBuilder("update " + getTableName() + " set ");
- Field[] fields = getEntityClass().getDeclaredFields();
- Scanner scanner = new Scanner(System.in);
- Class<?> enumClass = Class.forName(getEntityClass().getName() + "$COLUMNS");
- Method getValue = enumClass.getDeclaredMethod("getValue");
- Map<String, String> fieldsToColumnNames = new LinkedHashMap<>();
- Object[] columnNames = enumClass.getEnumConstants();
- for(int i = 0; i < fields.length; i++) {
- fields[i].setAccessible(true);
- fieldsToColumnNames.put(fields[i].getName(), (String) getValue.invoke(columnNames[i]));
- }
- String choice;
- for(Field field : fields) {
- if(field.getName().equals("ownerId")) {
- continue;
- }
- field.setAccessible(true);
- System.out.println("Would you like to change the value of " + field.getName() + " [y/Y] to change it.");
- System.out.print("Please enter your choice: ");
- choice = scanner.nextLine();
- String newValue = null;
- if(choice.equals("Y") || choice.equals("y")) {
- if(field.getType() == boolean.class) {
- System.out.print("Enter [y/Y] for true and anything else for false: ");
- newValue = scanner.nextLine();
- if(newValue.equals("Y") || newValue.equals("y")) {
- field.set(entity, 1);
- } else {
- field.set(entity, 0);
- }
- } else {
- System.out.print("Enter value for: " + field.getName() + ": ");
- newValue = scanner.nextLine();
- field.set(entity, newValue);
- }
- if(field.getType() == String.class) {
- updateStatementBuilder.append(fieldsToColumnNames.get(field.getName()) + " = " + "'" + newValue + "'" + ", ");
- } else {
- updateStatementBuilder.append(fieldsToColumnNames.get(field.getName()) + " = " + newValue + ", ");
- }
- }
- }
- updateStatementBuilder.replace(updateStatementBuilder.length() - 2, updateStatementBuilder.length(), " where id=" + id);
- System.out.println(updateStatementBuilder.toString());
- Statement updateStatement = getConn().createStatement();
- updateStatement.executeUpdate(updateStatementBuilder.toString());
- } else {
- System.out.println("No " + getEntityClass().getSimpleName() + " to be updated");
- }
- }
- }
- import com.emiltsonev.entities.PlaylistSong;
- import com.emiltsonev.entities.Song;
- import java.sql.*;
- import java.util.LinkedList;
- import java.util.List;
- public class PlaylistSongDaoDbImpl {
- private final static String CONNECTION_STRING = "jdbc:mysql://localhost/black_sound?useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
- private final Connection conn;
- public PlaylistSongDaoDbImpl() throws ClassNotFoundException, SQLException {
- Class.forName("com.mysql.cj.jdbc.Driver");
- conn = DriverManager.getConnection(CONNECTION_STRING, "emil", "emil");
- }
- public void insert(int playlistId, int songId) throws SQLException {
- Statement statement = conn.createStatement();
- statement.executeUpdate("insert into playlists_songs values(" + playlistId + ", " + songId + ")");
- }
- public List<Song> getSongsByPlaylistId(int playlistId) throws SQLException {
- List<Song> songs = new LinkedList<>();
- try(Statement statement = conn.createStatement();
- ResultSet results = statement.executeQuery("select songs.id, songs.name, songs.author, songs.year from playlists_songs join songs on playlists_songs.song_id = songs.id where playlists_songs.playlist_id = " + playlistId)) {
- while(results.next()) {
- Song song = new Song();
- song.setId(results.getInt(1));
- song.setName(results.getString(2));
- song.setArtistName(results.getString(3));
- song.setYear(results.getString(4));
- songs.add(song);
- }
- }
- return songs;
- }
- public List<PlaylistSong> getAll() throws SQLException {
- List<PlaylistSong> playlistSongs = new LinkedList<>();
- try(Statement statement = conn.createStatement();
- ResultSet results = statement.executeQuery("select * from playlists_songs")) {
- while(results.next()) {
- playlistSongs.add(new PlaylistSong(results.getInt(1), results.getInt(2)));
- }
- }
- return playlistSongs;
- }
- }
- import com.emiltsonev.entities.Song;
- import java.io.IOException;
- import java.lang.reflect.InvocationTargetException;
- import java.sql.SQLException;
- public class SongDaoDbImpl extends BaseDaoDbImpl<Song>{
- private PlaylistSongDaoDbImpl playlistSongDao = new PlaylistSongDaoDbImpl();
- public SongDaoDbImpl(Class<Song> entityClass, String tableName) throws ClassNotFoundException, SQLException {
- super(entityClass, tableName);
- }
- @Override
- public void save(Song entity) throws IOException, IllegalAccessException, NoSuchFieldException, InstantiationException, SQLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
- super.save(entity);
- playlistSongDao.insert(1, entity.getId());
- }
- }
- import com.emiltsonev.dao.UserDao;
- import com.emiltsonev.entities.User;
- import java.io.IOException;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class UserDaoDbImpl extends BaseDaoDbImpl<User> implements UserDao {
- public UserDaoDbImpl(Class<User> entityClass, String tableName) throws ClassNotFoundException, SQLException {
- super(entityClass, tableName);
- }
- @Override
- public User login(String email, String password) throws NoSuchFieldException, InstantiationException, IllegalAccessException, IOException, SQLException {
- try(Statement statement = getConn().createStatement();
- ResultSet results = statement.executeQuery("select users.id, users.email, users.password, users.display_name, users.is_administrator from users where users.email = '" + email + "' and users.password = '" + password + "'")) {
- if(results.next()) {
- User user = new User();
- user.setId(results.getInt(1));
- user.setEmail(results.getString(2));
- user.setPassword(results.getString(3));
- user.setDisplayName(results.getString(4));
- user.setAdministrator(results.getInt(5) == 1);
- return user;
- }
- }
- return null;
- }
- }
- // Ето ги и репо-тата
- public class AuthenticationService {
- private User user;
- private UserDaoDbImpl userDao;
- private static AuthenticationService authenticationService = null;
- private AuthenticationService() throws SQLException, ClassNotFoundException {
- userDao = new UserDaoDbImpl(User.class, "users");
- }
- public static AuthenticationService instance() throws SQLException, ClassNotFoundException {
- if(authenticationService == null) {
- authenticationService = new AuthenticationService();
- }
- return authenticationService;
- }
- public User authenticateUser(String email, String pasword) throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException, SQLException {
- user = userDao.login(email, pasword);
- return user;
- }
- public User getUser() {
- return user;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement