Интернет-магазин цифровых ключей компьютерных игр

Выбор архитектуры приложения и средств разработки. Проектирование пользовательского интерфейса и базы данных. Реализация серверной и клиентской частей системы. Привязка доменного имени. Настройка инструментов для автоматического развертывания приложения.

Рубрика Программирование, компьютеры и кибернетика
Вид дипломная работа
Язык русский
Дата добавления 14.12.2019
Размер файла 1,7 M

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

session.beginTransaction();

Query query=session.createQuery("from Genre where id=:id");

query.setParameter("id",id);

Genre genre= (Genre) query.uniqueResult();

session.delete(genre);

session.getTransaction().commit();

session.close();

}

@Override

public void update(Genre updatedGenre) {

entityDAO.update(updatedGenre);

}

@Override

public void clear() {

Session session=HibernateUtil.getSession();

session.beginTransaction();

session.createQuery("delete from Genre").executeUpdate();

session.getTransaction().commit();

session.close();

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\dao\H2LanguageDAO.java

package ru.discoverivan.gameshop.db.dao;

import org.hibernate.Session;

import org.hibernate.query.Query;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

import ru.discoverivan.gameshop.db.HibernateUtil;

import ru.discoverivan.gameshop.db.entity.Language;

import java.util.List;

@Repository

public class H2LanguageDAO implements LanguageDAO {

H2EntityDAO<Language> entityDAO;

@Autowired

public void setEntityDAO(H2EntityDAO<Language> entityDAO) {

this.entityDAO = entityDAO;

}

@Override

public void add(Language language) {

entityDAO.add(language);

}

@Override

public Language get(int id) {

Session session= HibernateUtil.getSession();

session.beginTransaction();

Query query = session.createQuery("from Language where id=:id");

query.setParameter("id", id);

Language language= (Language) query.uniqueResult();

session.getTransaction().commit();

session.close();

return language;

}

@Override

public List<Language> getAll() {

Session session= HibernateUtil.getSession();

session.beginTransaction();

List<Language> languages = (List<Language>) session.createQuery("from Language").list();

session.getTransaction().commit();

session.close();

return languages;

}

@Override

public void delete(int id) {

Session session=HibernateUtil.getSession();

session.beginTransaction();

Query query=session.createQuery("from Language where id=:id");

query.setParameter("id",id);

Language language= (Language) query.uniqueResult();

session.delete(language);

session.getTransaction().commit();

session.close();

}

@Override

public void update(Language updatedLanguage) {

entityDAO.update(updatedLanguage);

}

@Override

public void clear() {

Session session=HibernateUtil.getSession();

session.beginTransaction();

session.createQuery("delete from Language").executeUpdate();

session.getTransaction().commit();

session.close();

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\dao\H2OrderDAO.java

package ru.discoverivan.gameshop.db.dao;

import org.hibernate.Session;

import org.hibernate.query.Query;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

import ru.discoverivan.gameshop.db.HibernateUtil;

import ru.discoverivan.gameshop.db.JDBCTemplate;

import ru.discoverivan.gameshop.db.entity.Game;

import ru.discoverivan.gameshop.db.entity.Order;

import java.util.Date;

import java.util.List;

@Repository

public class H2OrderDAO implements OrderDAO {

private H2EntityDAO<Order> entityDAO;

@Autowired

public void setEntityDAO(H2EntityDAO<Order> entityDAO) {

this.entityDAO = entityDAO;

}

@Override

public void add(Order order) {

entityDAO.add(order);

}

@Override

public Order get(int id) {

Session session= HibernateUtil.getSession();

session.beginTransaction();

Query query = session.createQuery("from Order where id=:id");

query.setParameter("id", id);

Order order= (Order) query.uniqueResult();

session.getTransaction().commit();

session.close();

return order;

}

@Override

public List<Order> getAll() {

Session session= HibernateUtil.getSession();

session.beginTransaction();

List<Order> orders = (List<Order>) session.createQuery("from Order").list();

session.getTransaction().commit();

session.close();

return orders;

}

public List<Order> getOrdersInTimeInterval(Date from, Date to){

Session session= HibernateUtil.getSession();

session.beginTransaction();

Query query = session.createQuery(

"from Order where (date >= :beginDate and date <= :endDate)"

);

query.setParameter("beginDate", from);

query.setParameter("endDate", to);

List<Order> orders = (List<Order>) query.list();

session.getTransaction().commit();

session.close();

return orders;

}

@Override

public void delete(int id) {

Session session=HibernateUtil.getSession();

session.beginTransaction();

Query query=session.createQuery("from Order where id=:id");

query.setParameter("id",id);

Order order= (Order) query.uniqueResult();

session.delete(order);

session.getTransaction().commit();

session.close();

}

@Override

public void update(Order updatedOrder) {

entityDAO.update(updatedOrder);

}

@Override

public int count() {

Session session= HibernateUtil.getSession();

session.beginTransaction();

Long count = (Long) session.createQuery("select count(*) from Order ").uniqueResult();

session.getTransaction().commit();

session.close();

return count.intValue();

}

@Override

public void clear() {

Session session=HibernateUtil.getSession();

session.beginTransaction();

session.createQuery("delete from Order").executeUpdate();

session.getTransaction().commit();

session.close();

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\dao\H2PlatformDAO.java

package ru.discoverivan.gameshop.db.dao;

import org.hibernate.Session;

import org.hibernate.query.Query;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

import ru.discoverivan.gameshop.db.HibernateUtil;

import ru.discoverivan.gameshop.db.entity.Genre;

import ru.discoverivan.gameshop.db.entity.Platform;

import java.util.List;

@Repository

public class H2PlatformDAO implements PlatformDAO {

H2EntityDAO<Platform> entityDAO;

@Autowired

public void setEntityDAO(H2EntityDAO<Platform> entityDAO) {

this.entityDAO = entityDAO;

}

@Override

public void add(Platform platform) {

entityDAO.add(platform);

}

@Override

public Platform get(int id) {

Session session= HibernateUtil.getSession();

session.beginTransaction();

Query query = session.createQuery("from Platform where id=:id");

query.setParameter("id", id);

Platform platform= (Platform) query.uniqueResult();

session.getTransaction().commit();

session.close();

return platform;

}

@Override

public List<Platform> getAll() {

Session session= HibernateUtil.getSession();

session.beginTransaction();

List<Platform> platforms = (List<Platform>) session.createQuery("from Platform").list();

session.getTransaction().commit();

session.close();

return platforms;

}

@Override

public void delete(int id) {

Session session=HibernateUtil.getSession();

session.beginTransaction();

Query query=session.createQuery("from Platform where id=:id");

query.setParameter("id",id);

Platform platform= (Platform) query.uniqueResult();

session.delete(platform);

session.getTransaction().commit();

session.close();

}

@Override

public void update(Platform updatedPlatform) {

entityDAO.update(updatedPlatform);

}

@Override

public void clear() {

Session session=HibernateUtil.getSession();

session.beginTransaction();

session.createQuery("delete from Platform").executeUpdate();

session.getTransaction().commit();

session.close();

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\dao\H2ProductDAO.java

package ru.discoverivan.gameshop.db.dao;

import org.hibernate.Session;

import org.hibernate.query.Query;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

import ru.discoverivan.gameshop.db.HibernateUtil;

import ru.discoverivan.gameshop.db.entity.Game;

import ru.discoverivan.gameshop.db.entity.Order;

import ru.discoverivan.gameshop.db.entity.Product;

import java.util.List;

@Repository

public class H2ProductDAO implements ProductDAO {

private H2EntityDAO<Product> entityDAO;

@Autowired

public void setEntityDAO(H2EntityDAO<Product> entityDAO) {

this.entityDAO = entityDAO;

}

@Override

public void add(Product product) {

entityDAO.add(product);

}

@Override

public Product get(int id) {

Session session = HibernateUtil.getSession();

session.beginTransaction();

Query query = session.createQuery("from Product where id=:id");

query.setParameter("id", id);

Product product = (Product) query.uniqueResult();

session.getTransaction().commit();

session.close();

return product;

}

@Override

public List<Product> getAllProductsByGame(Game game) {

Session session= HibernateUtil.getSession();

session.beginTransaction();

Query query = session.createQuery("from Product where game=:game");

query.setParameter("game", game);

List<Product> products = query.list();

session.getTransaction().commit();

session.close();

return products;

}

@Override

public List<Product> getAll() {

Session session= HibernateUtil.getSession();

session.beginTransaction();

List<Product> products = (List<Product>) session.createQuery("from Product").list();

session.getTransaction().commit();

session.close();

return products;

}

@Override

public void delete(int id) {

Session session=HibernateUtil.getSession();

session.beginTransaction();

Product product= get(id);

session.delete(product);

session.getTransaction().commit();

session.close();

}

@Override

public void update(Product updatedProduct) {

entityDAO.update(updatedProduct);

}

@Override

public int count() {

Session session= HibernateUtil.getSession();

session.beginTransaction();

Long count = (Long) session.createQuery("select count(*) from Product").uniqueResult();

session.getTransaction().commit();

session.close();

return count.intValue();

}

@Override

public void clear() {

Session session=HibernateUtil.getSession();

session.beginTransaction();

session.createQuery("delete from Product").executeUpdate();

session.getTransaction().commit();

session.close();

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\dao\H2UserDAO.java

package ru.discoverivan.gameshop.db.dao;

import org.hibernate.Session;

import org.hibernate.query.Query;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

import ru.discoverivan.gameshop.db.HibernateUtil;

import ru.discoverivan.gameshop.db.entity.Customer;

import ru.discoverivan.gameshop.db.entity.User;

import java.util.List;

@Repository

public class H2UserDAO implements UserDAO {

private H2EntityDAO<User> entityDAO;

@Autowired

public void setEntityDAO(H2EntityDAO<User> entityDAO) {

this.entityDAO = entityDAO;

}

@Override

public void add(User user) {

entityDAO.add(user);

}

@Override

public User get(int id) {

Session session= HibernateUtil.getSession();

session.beginTransaction();

Query query = session.createQuery("from User where id=:id");

query.setParameter("id", id);

User user= (User) query.uniqueResult();

session.getTransaction().commit();

session.close();

return user;

}

@Override

public User findByUsername(String username) {

Session session= HibernateUtil.getSession();

session.beginTransaction();

Query query = session.createQuery("from User where username=:username");

query.setParameter("username", username);

User user= (User) query.uniqueResult();

session.getTransaction().commit();

session.close();

return user;

}

@Override

public List<User> getAll() {

Session session= HibernateUtil.getSession();

session.beginTransaction();

List<User> users = (List<User>) session.createQuery("from User").list();

session.getTransaction().commit();

session.close();

return users;

}

@Override

public void delete(int id) {

Session session=HibernateUtil.getSession();

session.beginTransaction();

Query query=session.createQuery("from User where id=:id");

query.setParameter("id",id);

User user= (User) query.uniqueResult();

session.delete(user);

session.getTransaction().commit();

session.close();

}

@Override

public void update(User updatedUser) {

entityDAO.update(updatedUser);

}

@Override

public void clear() {

Session session=HibernateUtil.getSession();

session.beginTransaction();

session.createQuery("delete from User").executeUpdate();

session.getTransaction().commit();

session.close();

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\dao\StaticListGameDAO.java

package ru.discoverivan.gameshop.db.dao;

import ru.discoverivan.gameshop.db.entity.Game;

import java.util.ArrayList;

import java.util.List;

import java.util.NoSuchElementException;

public class StaticListGameDAO implements GameDAO {

private static List<Game> games = new ArrayList<>();

private static int counter = 0;

@Override

public void add(Game game){

game.setId(counter++);

games.add(game);

}

@Override

public Game get(int id){

for (Game game : games) {

if (game.getId() == id){

return game;

}

}

throw new NoSuchElementException();

}

@Override

public List<Game> getAll(){

return games;

}

@Override

public List<Game> getOrderedList(String fieldName, int limit) {

return null;

}

@Override

public List<Game> selectListByField(String fieldName, String fieldValue, int limit) {

return null;

}

@Override

public void delete(int id) {

games.remove(get(id));

}

@Override

public void update(Game updatedGame) {

}

@Override

public int count() {

return 0;

}

@Override

public void clear() {

counter = 0;

games.clear();

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\additional\Cart.java

package ru.discoverivan.gameshop.db.entity.additional;

import ru.discoverivan.gameshop.db.entity.Customer;

import ru.discoverivan.gameshop.db.entity.Game;

import java.util.Set;

public class Cart {

private int id;

private Customer customer;

private Set<Game> games;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public Customer getCustomer() {

return customer;

}

public void setCustomer(Customer customer) {

this.customer = customer;

}

public Set<Game> getGames() {

return games;

}

public void setGames(Set<Game> games) {

this.games = games;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\additional\ExternalProduct.java

package ru.discoverivan.gameshop.db.entity.additional;

import com.fasterxml.jackson.annotation.JsonProperty;

public class ExternalProduct {

@JsonProperty("game_id")

private String gameId;

@JsonProperty("licence_key")

private String licenceKey;

public String getGameId() {

return gameId;

}

public void setGameId(String gameId) {

this.gameId = gameId;

}

public String getLicenceKey() {

return licenceKey;

}

public void setLicenceKey(String licenceKey) {

this.licenceKey = licenceKey;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\additional\FullStats.java

package ru.discoverivan.gameshop.db.entity.additional;

public class FullStats {

private Integer ordersCount;

private Float ordersSum;

private GraphData ordersGraph;

public Integer getOrdersCount() {

return ordersCount;

}

public void setOrdersCount(Integer ordersCount) {

this.ordersCount = ordersCount;

}

public Float getOrdersSum() {

return ordersSum;

}

public void setOrdersSum(Float ordersSum) {

this.ordersSum = ordersSum;

}

public GraphData getOrdersGraph() {

return ordersGraph;

}

public void setOrdersGraph(GraphData ordersGraph) {

this.ordersGraph = ordersGraph;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\additional\GraphData.java

package ru.discoverivan.gameshop.db.entity.additional;

import java.util.*;

public class GraphData {

private List<String> labels;

private List<Number> data;

public GraphData(Map<String, Integer> m) {

labels = new ArrayList<>();

data = new ArrayList<>();

List<String> keys = new ArrayList<>(m.keySet());

Collections.sort(keys);

for (String s : keys) {

labels.add(s);

data.add(m.get(s));

}

}

public List<String> getLabels() {

return labels;

}

public void setLabels(List<String> labels) {

this.labels = labels;

}

public List<Number> getData() {

return data;

}

public void setData(List<Number> data) {

this.data = data;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\additional\ShortStats.java

package ru.discoverivan.gameshop.db.entity.additional;

public class ShortStats {

private Integer totalGames;

private Integer totalOrders;

private Integer totalCustomers;

public Integer getTotalGames() {

return totalGames;

}

public void setTotalGames(Integer totalGames) {

this.totalGames = totalGames;

}

public Integer getTotalOrders() {

return totalOrders;

}

public void setTotalOrders(Integer totalOrders) {

this.totalOrders = totalOrders;

}

public Integer getTotalCustomers() {

return totalCustomers;

}

public void setTotalCustomers(Integer totalCustomers) {

this.totalCustomers = totalCustomers;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\Customer.java

package ru.discoverivan.gameshop.db.entity;

import javax.persistence.*;

import java.io.Serializable;

import java.util.Set;

@Entity

@DiscriminatorValue("customer")

public class Customer extends User implements Serializable {

public String name;

private String email;

private Set<Order> orders;

@Column(name = "name")

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Column(name = "email", unique = true)

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

@OneToMany(mappedBy = "customer", cascade = CascadeType.MERGE, fetch = FetchType.EAGER)

public Set<Order> getOrders() {

return orders;

}

public void setOrders(Set<Order> orders) {

this.orders = orders;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\Game.java

package ru.discoverivan.gameshop.db.entity;

import javax.persistence.*;

import java.io.Serializable;

import java.util.Arrays;

import java.util.Date;

import java.util.Set;

@Entity

@Table(name = "game")

public class Game implements Serializable {

private int id;

private String title;

private String description;

private String posterImageUrl;

private Set<String> screenshotsUrls;

private Set<Language> languages;

private Set<Platform> platforms;

private Set<Genre> genres;

private Date releaseDate;

private String developer;

private float price;

private int amount;

private int views;

private int orderCount;

private int status;

private Date publishDate;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(name = "title")

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

@Column(name = "description", columnDefinition = "TEXT")

public String getDescription() {

return description;

}

public void setDescription(String description) {

this.description = description;

}

@Column(name = "poster_image_url")

public String getPosterImageUrl() {

return posterImageUrl;

}

public void setPosterImageUrl(String posterImageUrl) {

this.posterImageUrl = posterImageUrl;

}

@ElementCollection(fetch=FetchType.EAGER)

@CollectionTable(name = "game_screenshot", joinColumns = @JoinColumn(name = "game_id"))

@Column(name = "image_url")

public Set<String> getScreenshotsUrls() {

return screenshotsUrls;

}

public void setScreenshotsUrls(Set<String> screenshotsUrls) {

this.screenshotsUrls = screenshotsUrls;

}

@ManyToMany(fetch=FetchType.EAGER)

@JoinTable(name = "game_language", joinColumns = {

@JoinColumn(name = "game_id", nullable = false, updatable = false) },

inverseJoinColumns = { @JoinColumn(name = "language_id",

nullable = false, updatable = false) })

public Set<Language> getLanguages() {

Arrays.sort(languages.toArray());

return languages;

}

public void setLanguages(Set<Language> languages) {

this.languages = languages;

}

@ManyToMany(fetch=FetchType.EAGER)

@JoinTable(name = "game_platform", joinColumns = {

@JoinColumn(name = "game_id", nullable = false, updatable = false) },

inverseJoinColumns = { @JoinColumn(name = "platform_id",

nullable = false, updatable = false) })

public Set<Platform> getPlatforms() {

return platforms;

}

public void setPlatforms(Set<Platform> platforms) {

this.platforms = platforms;

}

@ManyToMany(fetch=FetchType.EAGER)

@JoinTable(name = "game_genre", joinColumns = {

@JoinColumn(name = "game_id", nullable = false, updatable = false) },

inverseJoinColumns = { @JoinColumn(name = "genre_id",

nullable = false, updatable = false) })

public Set<Genre> getGenres() {

return genres;

}

public void setGenres(Set<Genre> genres) {

this.genres = genres;

}

@Temporal(TemporalType.DATE)

@Column(name = "release_date")

public Date getReleaseDate() {

return releaseDate;

}

public void setReleaseDate(Date releaseDate) {

this.releaseDate = releaseDate;

}

@Column(name = "developer")

public String getDeveloper() {

return developer;

}

public void setDeveloper(String developer) {

this.developer = developer;

}

@Column(name = "price")

public float getPrice() {

return price;

}

public void setPrice(float price) {

this.price = price;

}

@Column(name = "amount")

public int getAmount() {

return amount;

}

public void setAmount(int amount) {

this.amount = amount;

}

@Column(name = "views")

public int getViews() {

return views;

}

public void setViews(int views) {

this.views = views;

}

@Column(name = "order_count")

public int getOrderCount() {

return orderCount;

}

public void setOrderCount(int orderCount) {

this.orderCount = orderCount;

}

@Column(name = "status")

public int getStatus() {

return status;

}

public void setStatus(int status) {

this.status = status;

}

@Temporal(TemporalType.TIMESTAMP)

@Column(name = "publish_date", nullable = false, columnDefinition="DATETIME")

public Date getPublishDate() {

return publishDate;

}

public void setPublishDate(Date publishDate) {

this.publishDate = publishDate;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\Genre.java

package ru.discoverivan.gameshop.db.entity;

import javax.persistence.*;

import java.io.Serializable;

@Entity

@Table(name = "genre")

public class Genre implements Serializable {

private int id;

private String name;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(name = "name")

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\Language.java

package ru.discoverivan.gameshop.db.entity;

import javax.persistence.*;

import java.io.Serializable;

@Entity

@Table(name = "language")

public class Language implements Serializable {

private int id;

private String name;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(name = "name")

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\Order.java

package ru.discoverivan.gameshop.db.entity;

import javax.persistence.*;

import java.util.Date;

import java.util.Set;

@Entity

@Table(name = "orders")

public class Order {

private int id;

private Date date;

private Customer customer;

private Set<Product> products;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Temporal(TemporalType.TIMESTAMP)

@Column(name = "date", columnDefinition="DATETIME")

public Date getDate() {

return date;

}

public void setDate(Date date) {

this.date = date;

}

@ManyToOne(cascade = CascadeType.MERGE)

public Customer getCustomer() {

return customer;

}

public void setCustomer(Customer customer) {

this.customer = customer;

}

@OneToMany(fetch = FetchType.EAGER)

@JoinTable(

name="order_product",

joinColumns = @JoinColumn( name="order_id"),

inverseJoinColumns = @JoinColumn( name="product_id")

)

public Set<Product> getProducts() {

return products;

}

public void setProducts(Set<Product> products) {

this.products = products;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\Platform.java

package ru.discoverivan.gameshop.db.entity;

import javax.persistence.*;

import java.io.Serializable;

@Entity

@Table(name = "platform")

public class Platform implements Serializable {

private int id;

private String name;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(name = "name")

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\Product.java

package ru.discoverivan.gameshop.db.entity;

import javax.persistence.*;

@Entity

@Table(name = "product")

public class Product {

private int id;

private Game game;

private String key;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@ManyToOne

@JoinColumn(name="game_id")

public Game getGame() {

return game;

}

public void setGame(Game game) {

this.game = game;

}

@Column(name = "license_key")

public String getKey() {

return key;

}

public void setKey(String key) {

this.key = key;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\User.java

package ru.discoverivan.gameshop.db.entity;

import javax.persistence.*;

import java.util.Set;

@Entity

@Table(name = "user")

@DiscriminatorColumn(name = "discriminator")

public class User {

private int id;

private String username;

private String password;

private Set<UserRolesEnum> roles;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(name = "username", unique = true)

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

@Column(name = "password")

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

@ElementCollection(fetch = FetchType.EAGER)

@CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))

@Enumerated(EnumType.STRING)

@Column(name = "role")

public Set<UserRolesEnum> getRoles() {

return roles;

}

public void setRoles(Set<UserRolesEnum> roles) {

this.roles = roles;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\entity\UserRolesEnum.java

package ru.discoverivan.gameshop.db.entity;

public enum UserRolesEnum {

ADMIN,

CUSTOMER;

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\HibernateUtil.java

package ru.discoverivan.gameshop.db;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static final SessionFactory ourSessionFactory;

static {

try {

Configuration configuration = new Configuration();

configuration.configure();

ourSessionFactory = configuration.buildSessionFactory();

} catch (Throwable ex) {

throw new ExceptionInInitializerError(ex);

}

}

public static Session getSession() throws HibernateException {

return ourSessionFactory.openSession();

}

public static void close() {

ourSessionFactory.close();

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\db\JDBCTemplate.java

package ru.discoverivan.gameshop.db;

import java.sql.*;

public class JDBCTemplate implements AutoCloseable {

private Connection connection;

public JDBCTemplate(String url, String user, String password) {

try {

Class.forName("org.h2.Driver");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

try {

connection = DriverManager.getConnection(url, user, password);

} catch (SQLException e) {

e.printStackTrace();

}

}

public JDBCTemplate() {

this("jdbc:h2:~/database","root", "root");

}

public ResultSet query(String q, Object ... params) {

try {

PreparedStatement preparedStatement = createPreparedStatement(q, params);

if (preparedStatement != null) {

preparedStatement.execute();

return preparedStatement.getResultSet();

}

} catch (SQLException e) {

e.printStackTrace();

}

return null;

}

public ResultSet query(String q) {

try {

Statement statement = connection.createStatement();

statement.execute(q);

return statement.getResultSet();

} catch (SQLException e) {

e.printStackTrace();

}

return null;

}

public boolean execute(String q, Object ... params){

try (PreparedStatement preparedStatement = createPreparedStatement(q, params)) {

if (preparedStatement != null) {

return preparedStatement.execute();

}

} catch (SQLException e) {

e.printStackTrace();

}

return false;

}

public boolean execute(String q) {

try (Statement statement = connection.createStatement()) {

return statement.execute(q);

} catch (SQLException e) {

e.printStackTrace();

}

return false;

}

public int update(String q, Object ... params){

try (PreparedStatement preparedStatement = createPreparedStatement(q, params)){

if (preparedStatement != null) {

return preparedStatement.executeUpdate();

}

} catch (SQLException e) {

e.printStackTrace();

}

return 0;

}

public int update(String q){

try (Statement statement = connection.createStatement()) {

return statement.executeUpdate(q);

} catch (SQLException e) {

e.printStackTrace();

}

return 0;

}

private PreparedStatement createPreparedStatement(String q, Object ... params) {

try {

PreparedStatement preparedStatement = connection.prepareStatement(q);

int i = 1;

for (Object param : params) {

preparedStatement.setObject(i,param);

i++;

}

return preparedStatement;

} catch (SQLException e) {

e.printStackTrace();

}

return null;

}

@Override

public void close() {

try {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\domain\AdminService.java

package ru.discoverivan.gameshop.domain;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.stereotype.Service;

import ru.discoverivan.gameshop.db.dao.*;

import ru.discoverivan.gameshop.db.entity.*;

import java.util.Date;

import java.util.HashSet;

import java.util.Set;

@Service

public class AdminService {

private GameDAO gameDAO;

private OrderDAO orderDAO;

private CustomerDAO customerDAO;

private LanguageDAO languageDAO;

private GenreDAO genreDAO;

private PlatformDAO platformDAO;

private AdminDAO adminDAO;

private BCryptPasswordEncoder bCryptPasswordEncoder;

public void addGame(Game game) {

game.setPublishDate(new Date());

gameDAO.add(game);

}

@Autowired

public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {

this.bCryptPasswordEncoder = bCryptPasswordEncoder;

}

@Autowired

public void setAdminDAO(AdminDAO adminDAO) {

this.adminDAO = adminDAO;

}

@Autowired

public void setGameDAO(GameDAO gameDAO) {

this.gameDAO = gameDAO;

}

@Autowired

public void setOrderDAO(OrderDAO orderDAO) {

this.orderDAO = orderDAO;

}

@Autowired

public void setCustomerDAO(CustomerDAO customerDAO) {

this.customerDAO = customerDAO;

}

@Autowired

public void setLanguageDAO(LanguageDAO languageDAO) {

this.languageDAO = languageDAO;

}

@Autowired

public void setGenreDAO(GenreDAO genreDAO) {

this.genreDAO = genreDAO;

}

@Autowired

public void setPlatformDAO(PlatformDAO platformDAO) {

this.platformDAO = platformDAO;

}

public void addLanguage(Language language){

languageDAO.add(language);

}

public void addGenre(Genre genre){

genreDAO.add(genre);

}

public void addPlatform(Platform platform){

platformDAO.add(platform);

}

public void editGame(Integer id, Game game) {

Game oldGame = gameDAO.get(id);

game.setId(oldGame.getId());

game.setPublishDate(oldGame.getPublishDate());

gameDAO.update(game);

}

public void deleteGame(Integer id){

gameDAO.delete(id);

}

public void deleteOrder(int id) {

orderDAO.delete(id);

}

public void deleteLanguage(int id) {languageDAO.delete(id);}

public void deleteGenre(int id) {genreDAO.delete(id);}

public void deletePlatform(int id) {platformDAO.delete(id);}

public void editLanguage(Integer id, Language language) {

Language editableLanguage = languageDAO.get(id);

editableLanguage.setName(language.getName());

languageDAO.update(editableLanguage);

}

public void editGenre(Integer id, Genre genre) {

Genre editabelGenre = genreDAO.get(id);

editabelGenre.setName(genre.getName());

genreDAO.update(editabelGenre);

}

public void editPlatform(Integer id, Platform platform) {

Platform editablePlatform = platformDAO.get(id);

editablePlatform.setName(platform.getName());

platformDAO.update(editablePlatform);

}

public void deleteCustomer(int id) {

customerDAO.delete(id);

}

public void registerNewAdmin(Admin admin){

admin.setPassword(bCryptPasswordEncoder.encode(admin.getPassword()));

Set<UserRolesEnum> roles = new HashSet<>();

roles.add(UserRolesEnum.ADMIN);

admin.setRoles(roles);

adminDAO.add(admin);

}

public void removeAdmin(int id){

adminDAO.delete(id);

}

public int test(){

return 0;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\domain\CartService.java

package ru.discoverivan.gameshop.domain;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import ru.discoverivan.gameshop.db.dao.GameDAO;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;

import java.net.URLEncoder;

import java.util.ArrayList;

import java.util.HashSet;

import java.util.Set;

@Service

public class CartService {

private GameDAO gameDAO;

public String addGameToCartCookie(String cartCookie, int gameId){

Set<Integer> cart = getCartFromCookie(cartCookie);

cart.add(gameId);

return getCookieFromCart(cart);

}

public String removeGameFromCartCookie(String cartCookie, Integer gameId) {

Set<Integer> cart = getCartFromCookie(cartCookie);

cart.remove(gameId);

return getCookieFromCart(cart);

}

public Set<Integer> getCartFromCookie(String cartCookie) {

ObjectMapper mapper = new ObjectMapper();

if (cartCookie == null){

cartCookie = "";

} else {

try {

cartCookie = URLDecoder.decode(cartCookie, "UTF-8");

} catch (UnsupportedEncodingException e) {

cartCookie = "";

}

}

try {

return mapper.readValue(cartCookie, mapper.getTypeFactory().constructCollectionType(HashSet.class, Integer.class));

} catch (IOException e) {

return new HashSet<>();

}

}

public String getCookieFromCart(Set<Integer> cart) {

ObjectMapper mapper = new ObjectMapper();

try {

return URLEncoder.encode(mapper.writeValueAsString(cart), "UTF-8");

} catch (IOException e) {

return "";

}

}

public Set<Integer> validateCart(Set<Integer> cart) {

Set<Integer> newCart = new HashSet<>();

for (Integer gid : cart) {

if (gameDAO.get(gid) != null){

newCart.add(gid);

}

}

return newCart;

}

@Autowired

public void setGameDAO(GameDAO gameDAO) {

this.gameDAO = gameDAO;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\domain\EmailService.java

package ru.discoverivan.gameshop.domain;

import com.sun.mail.smtp.SMTPTransport;

import org.springframework.stereotype.Service;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Session;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.websocket.server.ServerEndpoint;

import java.io.UnsupportedEncodingException;

import java.util.Date;

import java.util.Properties;

@Service

public class EmailService {

public void sendEmail(String email, String subject, String text) throws MessagingException, UnsupportedEncodingException {

Session session = getSession();

Message msg = getMessage(email, subject, text, session);

transportMessageViaSmtp(session, msg);

}

private void transportMessageViaSmtp(Session session, Message msg) throws MessagingException {

SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

t.connect(System.getProperty("mail.smtps.host"), "gameshop@discoverivan.ru", "root123456");

t.sendMessage(msg, msg.getAllRecipients());

t.close();

}

private Message getMessage(String toEmail, String subject, String text, Session session) throws MessagingException, UnsupportedEncodingException {

Message msg = new MimeMessage(session);

msg.setFrom(new InternetAddress("gameshop@discoverivan.ru", "GAMESHOP - Магазин игр"));

msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

msg.setSubject(subject);

msg.setContent(text,"text/html; charset=utf-8");

msg.setHeader("X-Mailer", "ShopService");

msg.setSentDate(new Date());

return msg;

}

private Session getSession() {

Properties props = System.getProperties();

props.put("mail.smtps.host","smtp.yandex.com");

props.put("mail.smtps.auth","true");

return Session.getInstance(props, null);

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\domain\PaginationService.java

package ru.discoverivan.gameshop.domain;

import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.List;

@Service

public class PaginationService<T> {

public List<List<T>> getPages(List<T> objects, int objectsPerPage){

List<List<T>> pages = new ArrayList<>();

int pagesCount = (int) Math.ceil((double) objects.size() / objectsPerPage);

int objectPointer = 0;

for (int i=0;i<pagesCount;i++){

pages.add(new ArrayList<>());

for(int j=0;j<objectsPerPage;j++){

if (objectPointer >= objects.size())

break;

pages.get(i).add(objects.get(objectPointer++));

}

}

return pages;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\domain\SecurityService.java

package ru.discoverivan.gameshop.domain;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.stereotype.Service;

@Service

public class SecurityService {

private AuthenticationManager authenticationManager;

private UserDetailsService userDetailsService;

public void autoLogin(String username, String password) {

UserDetails userDetails = userDetailsService.loadUserByUsername(username);

UsernamePasswordAuthenticationToken authenticationToken =

new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());

authenticationManager.authenticate(authenticationToken);

if (authenticationToken.isAuthenticated()) {

SecurityContextHolder.getContext().setAuthentication(authenticationToken)

}

}

@Autowired

public void setAuthenticationManager(AuthenticationManager authenticationManager) {

this.authenticationManager = authenticationManager;

}

@Autowired

public void setUserDetailsService(UserDetailsService userDetailsService) {

this.userDetailsService = userDetailsService;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\domain\ShopService.java

package ru.discoverivan.gameshop.domain;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import ru.discoverivan.gameshop.db.dao.CustomerDAO;

import ru.discoverivan.gameshop.db.dao.GameDAO;

import ru.discoverivan.gameshop.db.dao.OrderDAO;

import ru.discoverivan.gameshop.db.dao.ProductDAO;

import ru.discoverivan.gameshop.db.entity.*;

import javax.mail.MessagingException;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;

import java.net.URLEncoder;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.util.*;

import java.util.regex.Pattern;

@Service

public class ShopService {

private EmailService emailService;

private GameDAO gameDAO;

private OrderDAO orderDAO;

private CustomerDAO customerDAO;

private ProductDAO productDAO;

@Autowired

public void setProductDAO(ProductDAO productDAO) {

this.productDAO = productDAO;

}

@Autowired

public void setEmailService(EmailService emailService) {

this.emailService = emailService;

}

@Autowired

public void setGameDAO(GameDAO gameDAO) {

this.gameDAO = gameDAO;

}

@Autowired

public void setOrderDAO(OrderDAO orderDAO) {

this.orderDAO = orderDAO;

}

@Autowired

public void setCustomerDAO(CustomerDAO customerDAO) {

this.customerDAO = customerDAO;

}

public void gameViewed(int gameId){

Game game = gameDAO.get(gameId);

if(game != null) {

game.setViews(game.getViews() + 1);

gameDAO.update(game);

}

}

public Order createOrder(Set<Integer> gameIds, Customer customer){

Order newOrder = new Order();

newOrder.setCustomer(customer);

newOrder.setDate(new Date());

Set<Game> games = new HashSet<>();

for (Integer gameId : gameIds) {

games.add(gameDAO.get(gameId));

}

Set<Product> products = new HashSet<>();

for (Game game : games) {

Product product = new Product();

product.setGame(game);

product.setKey(generateLicenseKey());

productDAO.add(product);

products.add(product);

}

newOrder.setProducts(products);

orderDAO.add(newOrder);

return newOrder;

}

public void processOrder(Order order){

String subjectText = String.format("Заказ №%s в магазине Gameshop", order.getId());

StringBuffer emailText = new StringBuffer();

emailText.append(

String.format("<h1>Спасибо за покупку!</h1>" +

"<h3>Здравствуйте, %s!</h3>"+

"<h3>Детали заказа №%s:</h3>",

order.getCustomer().getName(),

order.getId()));

System.out.println(order.getProducts().size());

for (Product product : order.getProducts()) {

emailText.append(

String.format("<p>Ключ для игры <b>%s</b>: %s</p>",

product.getGame().getTitle(),

product.getKey()));

}

try {

emailService.sendEmail(order.getCustomer().getEmail(),subjectText, emailText.toString());

} catch (MessagingException | UnsupportedEncodingException e) {

e.printStackTrace();

}

}

private List<Game> getOrderGames(Order order){

return null;

}

private String licenseKeySymbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

private String generateLicenseKey(){

StringBuffer s = new StringBuffer();

Random r = new Random();

for (int i = 0; i < 4;i++){

for (int j = 0; j < 5; j++){

s.append(licenseKeySymbols.charAt(r.nextInt(licenseKeySymbols.length())));

}

s.append('-');

}

s.deleteCharAt(s.length()-1);

return s.toString();

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\domain\StatsService.java

package ru.discoverivan.gameshop.domain;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import ru.discoverivan.gameshop.db.dao.*;

import ru.discoverivan.gameshop.db.entity.Order;

import ru.discoverivan.gameshop.db.entity.Product;

import ru.discoverivan.gameshop.db.entity.additional.FullStats;

import ru.discoverivan.gameshop.db.entity.additional.GraphData;

import ru.discoverivan.gameshop.db.entity.additional.ShortStats;

import java.text.SimpleDateFormat;

import java.util.*;

@Service

public class StatsService {

private GameDAO gameDAO;

private OrderDAO orderDAO;

private CustomerDAO customerDAO;

@Autowired

public void setGameDAO(GameDAO gameDAO) {

this.gameDAO = gameDAO;

}

@Autowired

public void setOrderDAO(OrderDAO orderDAO) {

this.orderDAO = orderDAO;

}

@Autowired

public void setCustomerDAO(CustomerDAO customerDAO) {

this.customerDAO = customerDAO;

}

private int getTotalGameCount(){

return gameDAO.count();

}

private int getTotalOrderCount(){

return orderDAO.count();

}

private int getTotalCustomerCount(){

return customerDAO.count();

}

public ShortStats getShortStats(){

ShortStats shortStats = new ShortStats();

shortStats.setTotalOrders(getTotalOrderCount());

shortStats.setTotalGames(getTotalGameCount());

shortStats.setTotalCustomers(getTotalCustomerCount());

return shortStats;

}

private float getOrderSum(List<Order> orders){

float sum = 0;

for (Order order : orders) {

List<Product> products = new ArrayList<>(order.getProducts());

for (Product product : products) {

sum += product.getGame().getPrice();

}

}

return sum;

}

public FullStats getFullStats(String timeInterval) {

Date startDate = getStartDate(timeInterval);

List<Order> orders;

if (!timeInterval.equals("all")){

orders = orderDAO.getOrdersInTimeInterval(startDate, new Date());

} else {

orders = orderDAO.getAll();

}

FullStats fullStats = new FullStats();

fullStats.setOrdersSum(getOrderSum(orders));

fullStats.setOrdersCount(orders.size());

fullStats.setOrdersGraph(getOrdersGraphData(orders));

return fullStats;

}

private GraphData getOrdersGraphData(List<Order> orders) {

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

Map<String, Integer> data = new HashMap<>();

for (Order order : orders) {

if (!data.containsKey(format.format(order.getDate()))) {

data.put(format.format(order.getDate()), 1);

} else {

data.put(format.format(order.getDate()), data.get(format.format(order.getDate()))+1);

}

}

return new GraphData(data);

}

private Date getStartDate(String timeInterval) {

Date startDate = new Date();

Calendar cal = Calendar.getInstance();

cal.setTime(startDate);

switch (timeInterval){

case "today":

cal.add(Calendar.DATE, -1);

break;

case "7":

cal.add(Calendar.DATE, -7);

break;

case "30":

cal.add(Calendar.DATE, -30);

break;

case "90":

cal.add(Calendar.DATE, -90);

break;

case "180":

cal.add(Calendar.DATE, -180);

break;

}

if (timeInterval != "all"){

startDate = cal.getTime();

}

return startDate;

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\domain\UserDetailsService.java

package ru.discoverivan.gameshop.domain;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Service;

import ru.discoverivan.gameshop.db.dao.UserDAO;

import ru.discoverivan.gameshop.db.entity.User;

import ru.discoverivan.gameshop.db.entity.UserRolesEnum;

import java.util.HashSet;

import java.util.Set;

@Service

public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

private UserDAO userDao;

@Autowired

public void setUserDao(UserDAO userDao) {

this.userDao = userDao;

}

@Override

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

User user = userDao.findByUsername(username);

Set<GrantedAuthority> grantedAuthorities = new HashSet<>();

for (UserRolesEnum role : user.getRoles()) {

grantedAuthorities.add(new SimpleGrantedAuthority(role.name()));

}

return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);

}

}

Файл: gameshop\src\main\java\ru\discoverivan\gameshop\domain\UserService.java

package ru.discoverivan.gameshop.domain;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.stereotype.Service;

import ru.discoverivan.gameshop.db.dao.CustomerDAO;

import ru.discoverivan.gameshop.db.entity.Customer;

import ru.discoverivan.gameshop.db.entity.UserRolesEnum;

import java.util.HashSet;

import java.util.Set;

@Service

public class UserService{

private BCryptPasswordEncoder bCryptPasswordEncoder;

private CustomerDAO customerDAO;

@Autowired

public void setCustomerDAO(CustomerDAO customerDAO) {

this.customerDAO = customerDAO;

}

@Autowired

public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {

this.bCryptPasswordEncoder = bCryptPasswordEncoder;

}

public void registerNewCustomer(Customer customer){

customer.setPassword(bCryptPasswordEncoder.encode(customer.getPassword()));

Set<UserRolesEnum> roles = new HashSet<>();

roles.add(UserRolesEnum.CUSTOMER);

customer.setRoles(roles);

customerDAO.add(customer);<...


Подобные документы

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.