Разработка программного продукта для составления расписания репетитора

Анализ существующих решений для составления расписания репетитора. Разработка архитектуры программного продукта. Выбор инструментальных средств. Проектирование реляционной базы данных. Определение методики тестирования. Реализация интерфейса пользователя.

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

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

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

return dateEnd;

}

public void setDateEnd(Date dateEnd) {

this.dateEnd = dateEnd;

}

public Date getTimeStart() {

return timeStart;

}

public void setTimeStart(Date timeStart) {

this.timeStart = timeStart;

}

public Date getTimeEnd() {

return timeEnd;

}

public void setTimeEnd(Date timeEnd) {

this.timeEnd = timeEnd;

}

public String getComment() {

return comment;

}

public void setComment(String comment) {

this.comment = comment;

}

public Lesson getLesson() {

return lesson;

}

public void setLesson(Lesson lesson) {

this.lesson = lesson;

}

public Event() {

}

}

Листинг класса Journal

package com.rep.db.domain;

import com.fasterxml.jackson.annotation.JsonFormat;

import javax.persistence.*;

import java.util.Date;

@Entity

@Table(name = "JOURNAL")

public class Journal extends BaseEntity {

@ManyToOne

@JoinColumn(name = "ID_THEME",

private Theme theme;

@ManyToOne

@JoinColumn(name = "ID_LESSON")

private Lesson lesson;

@Temporal(value = TemporalType.DATE)

@Column(name = "DATE",

nullable = false)

@JsonFormat(shape = JsonFormat.Shape.STRING,

pattern="yyyy-MM-dd")

private Date date;

@Column(name = "HOMETASK")

private String hometask;

@Column(name = "LESSON_MARK")

private String lessonMark;

@Column(name = "HOMETASK_MARK")

private String hometaskMark;

@Column(name = "COMMENT")

private String comment;

public Theme getTheme() {

return theme;

}

public void setTheme(Theme theme) {

this.theme = theme;

}

public Lesson getLesson() {

return lesson;

}

public void setLesson(Lesson lesson) {

this.lesson = lesson;

}

public Date getDate() {

return date;

}

public void setDate(Date date) {

this.date = date;

}

public String getHometask() {

return hometask;

}

public void setHometask(String hometask) {

this.hometask = hometask;

}

public String getLessonMark() {

return lessonMark;

}

public void setLessonMark(String lessonMark) {

this.lessonMark = lessonMark;

}

public String getHometaskMark() {

return hometaskMark;

}

public void setHometaskMark(String hometaskMark) {

this.hometaskMark = hometaskMark;

}

public String getComment() {

return comment;

}

public void setComment(String comment) {

this.comment = comment;

}

@Override

public String toString() {

return "Journal{" +

"theme=" + theme +

", lesson=" + lesson +

", date=" + date +

", hometask='" + hometask + '\'' +

", lessonMark='" + lessonMark + '\'' +

", hometaskMark='" + hometaskMark + '\'' +

'}';

}

public Journal() {

}

}

Листинг класса Lesson

package com.rep.db.domain;

import javax.persistence.*;

import java.math.BigDecimal;

import java.util.HashSet;

import java.util.Set;

@Entity

@Table(name = "LESSON")

public class Lesson extends BaseEntity {

@OneToOne

@JoinColumn(name = "ID_EVENT",

foreignKey = @ForeignKey(name = "FK_LESSON_EVENT"))

private Event event;

@Column(name = "PRICE")

private BigDecimal price;

@ManyToOne

@JoinColumn(name = "ID_SUBJECT",

foreignKey = @ForeignKey(name = "fk_lesson_subject"))

private Subject subject;

@OneToOne

@JoinColumn(name = "ID_STUDENT", foreignKey = @ForeignKey(name = "FK_LESSON_STUDENT"))

private Student student;

@OneToMany(mappedBy = "lesson")

private Set<Journal> journals = new HashSet<>();

public Event getEvent() {

return event;

}

public void setEvent(Event event) {

this.event = event;

}

public BigDecimal getPrice() {

return price;

}

public void setPrice(BigDecimal price) {

this.price = price;

}

@Override

public String toString() {

return "Lesson{" +

"price=" + price +

'}';

}

public Subject getSubject() {

return subject;

}

public void setSubject(Subject subject) {

this.subject = subject;

}

public Student getStudent() {

return student;

}

public void setStudent(Student student) {

this.student = student;

}

public Set<Journal> getJournals() {

return journals;

}

public void setJournals(Set<Journal> journals) {

this.journals = journals;

}

public Lesson() {

}

}

Листинг класса RepeatCode

package com.rep.db.domain;

public enum RepeatCode {

DAILY,

WEEKLY

MONTHLY,

YEARLY,

NEVER

}

Листинг класса Student

package com.rep.db.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;

import javax.persistence.*;

import java.util.HashSet;

import java.util.Set;

@Entity

@Table(name = "STUDENT")

public class Student extends BaseEntity {

@JsonIgnore

@Column(name = "ID_TUTOR",

nullable = false)

private Long idTutor;

@Column(name = "FIRST_NAME",

length = 45,

nullable = false)

private String firstName;

@Column(name = "LAST_NAME",

length = 45)

private String lastName;

@Column(name = "ADDRESS")

private String address;

public Long getIdTutor() {

return idTutor;

}

public void setIdTutor(Long idTutor) {

this.idTutor = idTutor;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

@Override

public String toString() {

return "Student{" +

"tutor=" + idTutor +

", firstName='" + firstName + '\'' +

", lastName='" + lastName + '\'' +

", address='" + address + '\'' +

'}';

}

@OneToMany(mappedBy = "idStudent")

private Set<Contact> contacts = new HashSet<Contact>();

public Set<Contact> getContacts() {

return contacts;

}

public void setContacts(Set<Contact> contacts) {

this.contacts = contacts;

}

public Student() {

}

}

Листинг класса Subject

package com.rep.db.domain;

import javax.persistence.Column;

mport javax.persistence.Entity;

import javax.persistence.Table;

import javax.persistence.UniqueConstraint;

@Entity

@Table(name = "SUBJECT",

uniqueConstraints = @UniqueConstraint(

name = "UK_SUBJECT_ID_TUTOR_NAME",

columnNames = {"ID_TUTOR", "NAME"}))

public class Subject extends BaseEntity {

@Column(name = "ID_TUTOR",

nullable = false)

private Long idTutor;

@Column(name = "NAME",

nullable = false,

length = 100)

private String name;

public Long getIdTutor() {

return idTutor;

}

public void setIdTutor(Long idTutor) {

this.idTutor = idTutor;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Override

public String toString() {

return "Subject{" +

"name='" + name + '\'' +

'}';

}

public Subject() {

}

}

Листинг класса Theme

package com.rep.db.domain;

import javax.persistence.*;

@Entity

@Table(name = "THEME")

public class Theme extends BaseEntity {

@ManyToOne

@JoinColumn(name = "ID_SUBJECT",

foreignKey = @ForeignKey(name = "FK_THEME_SUBJECT"))

private Subject subject;

@Column(name = "NAME", nullable = false, length = 255)

private String name;

@Column(name = "COMMENT")

private String comment;

@Column(name = "ID_PARENT_THEME")

private Long idParentTheme;

public Subject getSubject() {

return subject;

}

public void setSubject(Subject subject) {

this.subject = subject;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getComment() {

return comment;

}

public void setComment(String comment) {

this.comment = comment;

}

public Long getIdParentTheme() {

return idParentTheme;

}

public void setIdParentTheme(Long idParentTheme) {

this.idParentTheme = idParentTheme;

}

@Override

public String toString() {

return "Theme{" +

"subject=" + subject +

", name='" + name + '\'' +

", comment='" + comment + '\'' +

", idParentTheme=" + idParentTheme +

'}';

}

public Theme() {

}

}

Листинг класса Tutor

package com.rep.db.domain;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Table;

import javax.persistence.UniqueConstraint;

@Entity

@Table(name = "TUTOR",

uniqueConstraints = @UniqueConstraint(

name = "UK_TUTOR_NAME_ADDRESS",

columnNames = {"NAME", "ADDRESS"}))

public class Tutor extends BaseEntity {

@Column(name = "NAME")

private String name;

@Column(name = "ADDRESS")

private String address;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

@Override

public String toString() {

return "Tutor{" +

"name='" + name + '\'' +

", address='" + address + '\'' +

'}';

}

public Tutor() {

}

}

Листинг класса Application

package com.rep;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.ApplicationContext;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication

@EnableJpaRepositories

public class Application {

public static void main(String[] args) {

ApplicationContext applicationContext = SpringApplication.run(Application.class, args);

}

}

Листинг интерфейса ContactNameRepository

package com.rep.db.repository;

import com.rep.db.domain.ContactName;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.repository.query.Param;

import org.springframework.stereotype.Repository;

@Repository

public interface ContactNameRepository extends JpaRepository<ContactName, Long> {

ContactName findByName(@Param("name") String name);

}

Листинг интерфейса ContactRepository

package com.rep.db.repository;

import com.rep.db.domain.Contact;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import java.util.List;

@Repository

public interface ContactRepository extends JpaRepository<Contact, Long> {

List<Contact> findByIdStudent(Long idStudent);

}

Листинг интерфейса EventRepository

package com.rep.db.repository;

import com.rep.db.domain.Event;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.jpa.repository.Query;

import org.springframework.data.repository.query.Param;

import org.springframework.stereotype.Repository;

import java.util.List;

@Repository

public interface EventRepository extends JpaRepository<Event, Long> {

@Query(value = "select * " +

"from Event e " +

"where e.id_tutor = :idTutor",

nativeQuery = true)

List<Event> Param("idTutor") Long idTutor);

@Query(value = "select * " +

"from Event e " +

"where e.id_tutor = :idTutor " +

"and e.date_start <= :to " +

"and (e.date_end >= :from " +

"or e.date_end is null)",

nativeQuery = true)

List<Event> findAllEventsBetweenDates(@Param("idTutor") Long idTutor, @Param("from") String from, @Param("to") String to);

}

Листинг интерфейса JournalRepository

package com.rep.db.repository;

import com.rep.db.domain.Journal;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.jpa.repository.Query;

import org.springframework.data.repository.query.Param;

import org.springframework.stereotype.Repository;

import java.util.Date;

import java.util.List;

@Repository

public interface JournalRepository extends JpaRepository<Journal, Long> {

@Query(value = "select * " +

"from journal j, lesson l, event e " +

"where e.id_tutor = :idTutor " +

"and j.id_lesson = l.id " +

"and l.id_event = e.id " +

"order by j.date desc " +

"limit :limit " +

"offset :offset",

nativeQuery = true)

List<Journal> findByTutor(@Param("idTutor") Long idTutor,

@Param("limit") int limit,

@Param("offset") int offset);

@Query(value = "select * " +

"from journal j, lesson l, event e " +

"where e.id_tutor = :idTutor " +

"and j.id_lesson = l.id " +

"and l.id_event = e.id " +

"and l.id = :idLesson " +

"and j.date = :date",

nativeQuery = true)

Journal findByLessonAndDate(@Param("idTutor") Long idTutor,

@Param("idLesson") Long idLesson,

@Param("date") Date date);

}

Листинг интерфейса LessonRepository

package com.rep.db.repository;

import com.rep.db.domain.Lesson;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

@Repository

public interface LessonRepository extends JpaRepository<Lesson, Long> {

}

Листинг интерфейса StudentRepository

package com.rep.db.repository;

import com.rep.db.domain.Student;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import java.util.List;

@Repository

public interface StudentRepository extends JpaRepository<Student, Long> {

List<Student> findByIdTutor(Long idTutor);

List<Student> findByIdTutorAndFirstName(Long idTutor, String firstName);

}

Листинг интерфейса SubjectRepository

package com.rep.db.repository;

import com.rep.db.domain.Subject;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import java.util.List;

@Repository

public interface extends JpaRepository<Subject, Long> {

List<Subject> findByIdTutor(Long idTutor);

}

Листинг интерфейса ThemeRepository

package com.rep.db.repository;

import com.rep.db.domain.Theme;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import java.util.List;

@Repository

public interfac extends JpaRepository<Theme, Long> {

List<Theme> findBySubjectId(Long idSubject);

List<Theme> findByIdParentTheme(Long idParentTheme);

}

Листинг интерфейса TutorRepository

package com.rep.db.repository;

import com.rep.db.domain.Tutor;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.repository.query.Param;

import org.springframework.stereotype.Repository;

@Repository

public interface TutorRepository extends JpaRepository<Tutor, Long> {

Tutor findByNameAndAddress(@Param("name") String name, @Param("address") String address);}

Листинг класса ContactNameService

package com.rep.core.services;

import com.rep.db.domain.ContactName;

import com.rep.db.repository.ContactNameRepository;

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

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class ContactNameService {

private ContactNameRepository contactNameRepository;

@Autowired

public ContactNameService(ContactNameRepository contactNameRepository) {

this.contactNameRepository = contactNameRepository;

}

public List<ContactName> listAllContactNames() {

return contactNameRepository.findAll();

}

public ContactName findById(long id) {

return contactNameRepository.findOne(id);

}

public ContactName findByName(String name) {

return contactNameRepository.findByName(name);

}

public ContactName createContactName(ContactName contactName) {

ContactName found = findByName(contactName.getName());

if (found != null) return found;

return contactNameRepository.saveAndFlush(contactName);

}

public ContactName updateContactName(ContactName contactName) {

return contactNameRepository.saveAndFlush(contactName);

}

public void deleteContactName(long id) {

contactNameRepository.delete(id);

}

}

Листинг класса EventService

package com.rep.core.services;

import com.rep.db.domain.Event;

import com.rep.db.repository.EventRepository;

import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.List;

@Service

public class EventService {

private EventRepository eventRepository;

public EventService(EventRepository eventRepository) {

this.eventRepository = eventRepository;

}

public List<Event> findAllEventsByIdTutor(Long idTutor) {

return eventRepository.findAllByIdTutor(idTutor);

}

public List<Event> findBetweenDates(Long idTutor, String from, String to) {

List<Event> result = new ArrayList<>();

result.addAll(eventRepository.findAllEventsBetweenDates(idTutor,

from,

to));

return result;

}

public Event createEvent(Event event) {

return eventRepository.saveAndFlush(event);

}

public Event findById(Long id) {

return eventRepository.findOne(id);

}

public Event updateEvent(Event event) {

return eventRepository.saveAndFlush(event);

}

public void deleteEventById(Long id) {

eventRepository.delete(id);

}

}

Листинг класса EventUtil

package com.rep.core.services;

import com.rep.core.dto.EventDto;

import com.rep.db.domain.Event;

import java.util.ArrayList;

import java.util.Comparator;

import java.util.Date;

import java.util.List;

import static com.rep.core.common.DateUtil.*;

public class EventUtil {

public static List<EventDto> formatAllEvents(List<Event> events, Date from, Date to) {

//Начальная дата события, попадающая в промежуток from-to, либо первая дата повторяющегося события, позже from

Date current;

//Старт серии событий

Date dateStart;

//Окончание серии событий

Date dateEnd;

//Результирующий список со всеми событиями, попадающими в промежуток from-to

ArrayList<EventDto> result = new ArrayList<>();

for (Event event : events) {

dateStart = event.getDateStart();

dateEnd = event.getDateEnd();

switch (event.getRepeatCode()) {

case NEVER:

//Для неповторяющихся событий достаточно проверить, что его дата попадает в нужный промежуток

if (afterOrEqual(dateStart, from) && beforeOrEqual(dateStart, to))

{

result.add(EventDto.of(event, dateStart));

}

break;

case DAILY:

//Начальной датой становится начало промежутка, если оно позже, чем начало серии событий

current = new Date(afterOrEqual(from, dateStart) ? from.getTime() : dateStart.getTime());

//Пока текущая дата <= конца промежутка и <= даты окончания серии событий (либо событие "бесконечное"),

while (beforeOrEqual(current, to)

&& (dateEnd == null || beforeOrEqual(current, dateEnd))) {

//формируем события каждый день

result.add(EventDto.of(event, current));

current = nextDay(current);

}

break;

case WEEKLY:

//Если событие начинается раньше, чем начало промежутка,

if (dateStart.before(from)) {

//вычисляем количество недель для сдвига, чтобы дата начала стала >= даты начала промежутка

long days = (from.getTime() - dateStart.getTime()) / (1000 * 60 * 60 * 24) - 1;

long weeks = days / 7 + 1;

//сдвигаем дату начала на нужное количество недель

current = new Date(dateStart.getTime() + weeks * 7 * 24 * 60 * 60 * 1000);

} else { //Иначе дата начала подходит, т.к. попадает в промежуток

current = new Date(dateStart.getTime());

}

//Заполняем промежуток еженедельными событиями

while (beforeOrEqual(current, to)

&& (dateEnd == null || beforeOrEqual(current, dateEnd))) {

result.add(EventDto.of(event, current));

current = nextWeek(current);

}

break;

case MONTHLY:

//Начинаем с даты начала серии событий

current = new Date(dateStart.getTime());

//Назначаем год и месяц промежутка для начальной даты

if (current.before(from)) {

current.setYear(from.getYear());

current.setMonth(from.getMonth());

}

//Если начальная дата все еще меньше начала промежутка, сдвигаем еще на месяц

if (current.before(from)) {

current = nextMonth(current);

}

//Добавляем в результирующий список ежемесячные события

while (beforeOrEqual(current, to)

&& (dateEnd == null || beforeOrEqual(current, dateEnd))) {

result.add(EventDto.of(event, current));

current = nextMonth(current);

}

break;

case YEARLY:

//Начинаем с даты начала серии событий

current = new Date(dateStart.getTime());

//Меняем год на тот, с которого начинается промежуток

if (current.before(from))

current.setYear(from.getYear());

//Если начальная дата все еще меньше начала промежутка, сдвигаем еще на год

if (current.before(from))

current = nextYear(current);

//Добавляем в список ежегодные события

while (beforeOrEqual(current, to)

&& (dateEnd == null || beforeOrEqual(current, dateEnd))) {

result.add(EventDto.of(event, current));

current = nextYear(current);

}

break;

}

}

result.sort(Comparator.comparing(EventDto::getCurrentDate));

return result;

}

}

Листинг класса JournalService

package com.rep.core.services;

import com.rep.db.domain.Journal;

import com.rep.db.repository.JournalRepository;

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

import org.springframework.stereotype.Service;

import java.util.Date;

import java.util.List;

@Service

public class JournalService {

private JournalRepository journalRepository;

@Autowired

public JournalService(JournalRepository journalRepository) {

this.journalRepository = journalRepository;

}

public Journal find(Long idTutor, Long idLesson, Date date) {

return journalRepository.findByLessonAndDate(idTutor, idLesson, date);

}

public List<Journal> findPageable(Long idTutor, int limit, int offset) {

return journalRepository.findByTutor(idTutor, limit, offset);

}

public Journal create(Journal journal) {

return journalRepository.saveAndFlush(journal);

}

public Journal findById(Long id) {

return journalRepository.findOne(id);

}

public Journal updateJournal(Journal journal) {

return journalRepository.saveAndFlush(journal);

}

}

Листинг класса LessonService

package com.rep.core.services;

import com.rep.db.repository.LessonRepository;

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

import org.springframework.stereotype.Service;

@Service

public class LessonService {

private LessonRepository lessonRepository;

@Autowired

public LessonService(LessonRepository lessonRepository) {

this.lessonRepository = lessonRepository;

}

}

Листинг класса StudentContactService

package com.rep.core.services;

import com.rep.db.domain.Contact;

import com.rep.db.domain.ContactName;

import com.rep.db.domain.Student;

import com.rep.db.repository.ContactNameRepository;

import com.rep.db.repository.ContactRepository;

import com.rep.db.repository.StudentRepository;

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

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service

public class StudentContactService {

private final StudentRepository studentRepository;

private final ContactRepository contactRepository;

private final ContactNameRepository contactNameRepository;

@Autowired

public StudentContactService(StudentRepository studentRepository, ContactRepository contactRepository, ContactNameRepository contactNameRepository) {

this.studentRepository = studentRepository;

this.contactRepository = contactRepository;

this.contactNameRepository = contactNameRepository;

}

public Contact findContactById(Long id) {

return contactRepository.findOne(id);

}

public List<Contact> findContactsByIdStudent(Long idStudent) {

return contactRepository.findByIdStudent(idStudent);

}

public void deleteContact(Long id) {

contactRepository.delete(id);

}

@Transactional

public Contact createOrUpdateContact(Contact contact) {

ContactName contactName = contact.getContactName();

ContactName found = contactNameRepository.findByName(contactName.getName());

if (found == null) {

found = contactNameRepository.saveAndFlush(contactName);

}

contact.setContactName(found);

return contactRepository.saveAndFlush(contact);

}

@Transactional

public Student createOrUpdateStudent(Student student) {

Student saved = studentRepository.saveAndFlush(student);

for (Contact contact : student.getContacts()) {

contact.setIdStudent(saved.getId());

ContactName savedContactName = contactNameRepository.findByName(contact.getContactName().getName());

if (savedContactName == null) {

savedContactName = contactNameRepository.saveAndFlush(contact.getContactName());

}

contact.setContactName(savedContactName);

contactRepository.saveAndFlush(contact);

}

//Удаляем старые ненужные контакты по id

List<Contact> oldContacts = contactRepository.findByIdStudent(student.getId());

for (Contact oldContact : oldContacts) {

boolean contains = false;

for (Contact newContact : student.getContacts()) {

if (oldContact.getId().equals(newContact.getId())) {

contains = true;

}

}

if (!contains) {

contactRepository.delete(oldContact.getId());

}

}

return saved;

}

public Student findStudentById(Long id) {

return studentRepository.findOne(id);

}

public void deleteStudent(Long id) {

studentRepository.delete(id);

}

public List<Student> findStudentsByIdTutor(Long idTutor) {

return studentRepository.findByIdTutor(idTutor);

}

public List<Student> findStudentsByIdTutorAndFirstName(Long idTutor, String firstName) {

return studentRepository.findByIdTutorAndFirstName(idTutor, firstName);

}

}

Листинг класса SubjectThemeService

package com.rep.core.services;

import com.rep.core.dto.ThemeDto;

import com.rep.db.domain.Subject;

import com.rep.db.domain.Theme;

import com.rep.db.repository.SubjectRepository;

import com.rep.db.repository.ThemeRepository;

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

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class SubjectThemeService {

private final SubjectRepository subjectRepository;

private final ThemeRepository themeRepository;

@Autowired

public SubjectThemeService(SubjectRepository subjectRepository, ThemeRepository themeRepository) {

this.subjectRepository = subjectRepository;

this.themeRepository = themeRepository;

}

public Subject createSubject(Subject subject) {

Subject saved = subjectRepository.saveAndFlush(subject);

Theme theme = new Theme();

theme.setSubject(saved);

theme.setName(saved.getName());

themeRepository.saveAndFlush(theme);

return saved;

}

public Theme createTheme(Theme theme) {

return themeRepository.saveAndFlush(theme);

}

public Theme findThemeById(Long id) {

return themeRepository.findOne(id);

}

public List<Theme> findThemesByIdSubject(Long idSubject) {

return themeRepository.findBySubjectId(idSubject);

}

public List<Theme> findThemesByIdParent(Long idParent) {

return themeRepository.findByIdParentTheme(idParent);

}

public List<ThemeDto> findTreeByIdParent(Long idParent) {

List<ThemeDto> result = ThemeDto.of(themeRepository.findByIdParentTheme(idParent));

if (result.size() == 0) {

return null;

} else {

for (ThemeDto theme : result) {

theme.setChildren(findTreeByIdParent(theme.getId()));

}

}

return result;

}

public void deleteThemeById(Long id) {

List<Theme> children = themeRepository.findByIdParentTheme(id);

for (Theme theme : children) {

deleteThemeById(theme.getId());

}

themeRepository.delete(id);

}

}

Листинг класса TutorService

package com.rep.core.services;

import com.rep.core.dto.TutorDto;

import com.rep.db.domain.Tutor;

import com.rep.db.repository.TutorRepository;

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

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class TutorService {

private TutorRepository tutorRepository;

@Autowired

public TutorService(TutorRepository tutorRepository) {

this.tutorRepository = tutorRepository;

}

public List<Tutor> listAllTutors() {

return tutorRepository.findAll();

}

public Tutor findById(Long id) {

return tutorRepository.findOne(id);

}

private Tutor createByNameAndAddress(String name, String address) {

Tutor found = tutorRepository.findByNameAndAddress(name, address);

if (found != null)

return found;

Tutor tutor = new Tutor();

tutor.setName(name);

tutor.setAddress(address);

return tutorRepository.saveAndFlush(tutor);

}

public Tutor createTutor(TutorDto tutorDto) {

return createByNameAndAddress(tutorDto.getName(), tutorDto.getAddress());

}

public Tutor updateTutor(Tutor tutor) {

return tutorRepository.saveAndFlush(tutor);

}

public void deleteTutor(Long id) {

tutorRepository.delete(id);

}

}

Листинг класса RestContactController

package com.rep.core.restControllers;

import com.rep.core.services.StudentContactService;

import com.rep.db.domain.Contact;

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

import org.springframework.http.HttpHeaders;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

import static org.springframework.http.HttpStatus.*;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@RestController

@RequestMapping("/rest/student/{idStudent}/contact")

public class RestContactController {

private final StudentContactService studentContactService;

@Autowired

public RestContactController(StudentContactService contactService) {

this.studentContactService = contactService;

}

@RequestMapping(method = GET)

public ResponseEntity<List<Contact>> findAllByIdStudent(@PathVariable("idStudent") Long idStudent) {

List<Contact> contacts = studentContactService.findContactsByIdStudent(idStudent);

if (contacts.isEmpty()) {

return new ResponseEntity<>(NOT_FOUND);

}

return new ResponseEntity<>(contacts, OK);

}

@RequestMapping(method = GET, path = "/{id}")

public ResponseEntity<Contact> findById(@PathVariable("id") Long id,

@PathVariable("idStudent") Long idStudent) {

Contact contact = studentContactService.findContactById(id);

if (contact == null || !contact.getIdStudent().equals(idStudent)) {

return new ResponseEntity<>(NOT_FOUND);

}

return new ResponseEntity<>(contact, OK);

}

@RequestMapping(method = POST)

public ResponseEntity<Void> createContact(@PathVariable("idStudent") Long idStudent,

@RequestBody Contact contact,

UriComponentsBuilder ucBuilder) {

contact.setIdStudent(idStudent);

Contact saved = studentContactService.createOrUpdateContact(contact);

HttpHeaders headers = new HttpHeaders();

headers.setLocation(ucBuilder

.path("/rest/student/{idStudent}/contact/{id}")

.buildAndExpand(

saved.getIdStudent(),

saved.getId())

.toUri());

return new ResponseEntity<>(headers, CREATED);

}

@RequestMapping(method = PUT, path = "/{id}")

public ResponseEntity<Contact> updateContact(@PathVariable("idStudent") Long idStudent,

@PathVariable("id") Long id,

@RequestBody Contact contact) {

Contact found = studentContactService.findContactById(id);

if (found == null || !found.getIdStudent().equals(idStudent)) {

return new ResponseEntity<>(NOT_FOUND);

}

contact.setId(id);

contact.setIdStudent(idStudent);

found = studentContactService.createOrUpdateContact(contact);

return new ResponseEntity<>(found, OK);

}

@RequestMapping(method = DELETE, path = "/{id}")

public ResponseEntity<Void> deleteContact(@PathVariable("idStudent") Long idStudent,

@PathVariable("id") Long id) {

Contact found = studentContactService.findContactById(id);

if (found == null || !found.getIdStudent().equals(idStudent)) {

return new ResponseEntity<>(NOT_FOUND);

}

studentContactService.deleteContact(id);

return new ResponseEntity<>(NO_CONTENT);

}

}

Листинг класса RestContactNameController

package com.rep.core.restControllers;

import com.rep.core.services.ContactNameService;

import com.rep.db.domain.ContactName;

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

import org.springframework.http.HttpHeaders;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

import static org.springframework.http.HttpStatus.*;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@CrossOrigin

@RestController

@RequestMapping("/rest/contactname")

public class RestContactNameController {

private ContactNameService contactNameService;

@Autowired

public RestContactNameController(ContactNameService contactNameService) {

this.contactNameService = contactNameService;

}

@RequestMapping(method = GET)

public ResponseEntity<List<ContactName>> findAllContactNames(@RequestHeader("idTutor") Long idTutor) {

List<ContactName> contactNames = contactNameService.listAllContactNames();

if (contactNames.isEmpty()) {

return new ResponseEntity<>(NOT_FOUND);

}

return new ResponseEntity<>(contactNames, OK);

}

@RequestMapping(method = GET, path = "/{id}")

public ResponseEntity<ContactName> getContactName(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id) {

ContactName found = contactNameService.findById(id);

return new ResponseEntity<>(found, OK);

}

@RequestMapping(method = POST)

public ResponseEntity<Void> createContactName(@RequestHeader("idTutor") Long idTutor,

@RequestBody ContactName contactName,

UriComponentsBuilder ucBuilder) {

ContactName saved = contactNameService.createContactName(contactName);

HttpHeaders headers = new HttpHeaders();

headers.setLocation(ucBuilder.path("/rest/contactname/{id}").buildAndExpand(saved.getId()).toUri());

return new ResponseEntity<>(headers, CREATED);

}

@RequestMapping(method = PUT, path = "/{id}")

public ResponseEntity<ContactName> updateContactName(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id,

@RequestBody ContactName contactName) {

contactName.setId(id);

ContactName found = contactNameService.updateContactName(contactName);

return new ResponseEntity<>(found, OK);

}

@RequestMapping(method = DELETE, path = "/{id}")

public ResponseEntity<ContactName> deleteContactName(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id) {

ContactName found = contactNameService.findById(id);

contactNameService.deleteContactName(id);

return new ResponseEntity<>(NO_CONTENT);

}

}

Листинг класса RestEventController

package com.rep.core.restControllers;

import com.rep.core.dto.EventDto;

import com.rep.core.services.EventService;

import com.rep.core.services.EventUtil;

import com.rep.db.domain.Event;

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

import org.springframework.http.HttpHeaders;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

import static com.rep.core.common.DateUtil.toDate;

import static org.springframework.http.HttpStatus.*;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@CrossOrigin

@RestController

@RequestMapping("/rest/event")

public class RestEventController {

private final EventService eventService;

@Autowired

public RestEventController(EventService eventService) {

this.eventService = eventService;

}

@RequestMapping(method = GET)

public ResponseEntity<List<Event>> listAllEventsByIdTutor(@RequestHeader("idTutor") Long idTutor) {

List<Event> events;

events = eventService.findAllEventsByIdTutor(idTutor);

if (events.isEmpty()) {

return new ResponseEntity<>(NOT_FOUND);

}

return new ResponseEntity<>(events, OK);

}

@RequestMapping(method = GET, params = {"from", "to"})

public ResponseEntity<List<EventDto>> listAllEvents(@RequestHeader("idTutor") Long idTutor,

@RequestParam(value = "from") String from,

@RequestParam(value = "to") String to) {

List<Event> events = eventService.findBetweenDates(idTutor, from, to);

if (events.isEmpty()) {

return new ResponseEntity<>(NO_CONTENT);

}

List<EventDto> dtos = EventUtil.formatAllEvents(events, toDate(from), toDate(to));

return new ResponseEntity<>(dtos, OK);

}

@RequestMapping(method = GET, path = "/{id}")

public ResponseEntity<EventDto> eventById(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id) {

Event found = eventService.findById(id);

if (found == null || !found.getIdTutor().equals(idTutor)) {

return new ResponseEntity<>(NOT_FOUND);

}

return new ResponseEntity<>(EventDto.of(found, null), OK);

}

@RequestMapping(method = POST)

public ResponseEntity<Void> createEvent(@RequestHeader("idTutor") Long idTutor,

@RequestBody Event event,

UriComponentsBuilder ucBuilder) {

event.setIdTutor(idTutor);

Event saved = eventService.createEvent(event);

HttpHeaders headers = new HttpHeaders();

headers.setLocation(ucBuilder.path("/rest/event/{id}").buildAndExpand(saved.getIdTutor(), saved.getId()).toUri());

return new ResponseEntity<>(headers, CREATED);

}

@RequestMapping(method = PUT, value = "/{id}")

public ResponseEntity<Event> updateEvent(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id,

@RequestBody Event event) {

Event found = eventService.findById(id);

if (found == null || !found.getIdTutor().equals(idTutor)) {

return new ResponseEntity<>(NOT_FOUND);

}

event.setIdTutor(idTutor);

event.setId(id);

found = eventService.updateEvent(event);

return new ResponseEntity<>(found, OK);

}

@RequestMapping(method = DELETE, value = "/{id}")

public ResponseEntity<Void> deleteEvent(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") long id) {

Event found = eventService.findById(id);

if (found == null || !found.getIdTutor().equals(idTutor)) {

return new ResponseEntity<>(NOT_FOUND);

}

eventService.deleteEventById(id);

return new ResponseEntity<>(NO_CONTENT);

}

}

Листинг класса RestJournalController

package com.rep.core.restControllers;

import com.rep.core.dto.JournalDto;

mport com.rep.core.services.JournalService;

import com.rep.core.common.DateUtil;

import com.rep.db.domain.Journal;

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

import org.springframework.http.HttpHeaders;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

import static org.springframework.http.HttpStatus.*;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

import static org.springframework.web.bind.annotation.RequestMethod.PUT;

@CrossOrigin

@RestController

@RequestMapping(path = "/rest/journal")

public class RestJournalController {

private JournalService journalService;

@Autowired

public RestJournalController(JournalService journalService) {

this.journalService = journalService;

}

@RequestMapping(method = GET, path = "/idLesson/{idLesson}", params = {"date"})

public ResponseEntity<JournalDto> getByLessonAndDate(@RequestHeader("idTutor") Long idTutor,

@PathVariable("idLesson") Long idLesson,

@RequestParam(value = "date") String date) {

Journal found = journalService.find(idTutor, idLesson, DateUtil.toDate(date));

if (found == null) {

return new ResponseEntity<>(NO_CONTENT);

}

return new ResponseEntity<>(JournalDto.of(found), OK);

}

@RequestMapping(method = GET, params = {"limit", "offset"})

public ResponseEntity<List<JournalDto>> getJournals(@RequestHeader("idTutor") Long idTutor,

@RequestParam(value = "limit") int limit,

@RequestParam(value = "offset") int offset) {

List<Journal> found = journalService.findPageable(idTutor, limit, offset);

if (found == null || found.isEmpty()) {

return new ResponseEntity<>(NO_CONTENT);

}

return new ResponseEntity<>(JournalDto.of(found), OK);

}

@RequestMapping(method = POST)

public ResponseEntity<Void> createContactName(@RequestHeader("idTutor") Long idTutor,

@RequestBody Journal journal,

UriComponentsBuilder ucBuilder) {

Journal saved = journalService.create(journal);

HttpHeaders headers = new HttpHeaders();

headers.setLocation(ucBuilder.path("/rest/journal/{id}").buildAndExpand(saved.getId()).toUri());

return new ResponseEntity<>(headers, CREATED);

}

@RequestMapping(method = GET, path = "/{id}")

public ResponseEntity<JournalDto> getJournalById(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id) {

Journal found = journalService.findById(id);

if (found == null || !idTutor.equals(found.getLesson().getEvent().getIdTutor())) {

return new ResponseEntity<>(NO_CONTENT);

}

return new ResponseEntity<>(JournalDto.of(found), OK);

}

@RequestMapping(method = PUT, path = "/{id}")

public ResponseEntity<JournalDto> updateJournal(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id,

@RequestBody Journal journal) {

Journal found = journalService.findById(id);

if (found == null || !idTutor.equals(found.getLesson().getEvent().getIdTutor())) {

return new ResponseEntity<>(NOT_FOUND);

}

journal.setId(id);

journal.setDate(found.getDate());

journal.setLesson(found.getLesson());

Journal saved = journalService.updateJournal(journal);

return new ResponseEntity<>(JournalDto.of(saved), OK);

}

}

Листинг класса RestStudentController

package com.rep.core.restControllers;

import com.rep.core.services.StudentContactService;

import com.rep.db.domain.Student;

import org.springframework.http.HttpHeaders;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

import static org.springframework.http.HttpStatus.*;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@CrossOrigin

@RestController

@RequestMapping("/rest/student")

public class RestStudentController {

private final StudentContactService studentContactService;

public RestStudentController(StudentContactService studentContactService) {

this.studentContactService = studentContactService;

}

@RequestMapping(method = GET, path = "/{id}")

public ResponseEntity<Student> findById(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id) {

Student found = studentContactService.findStudentById(id);

if (found == null || !found.getIdTutor().equals(idTutor)) {

return new ResponseEntity<Student>(NOT_FOUND);

}

return new ResponseEntity<Student>(found, OK);

}

@RequestMapping(method = GET)

public ResponseEntity<List<Student>> findByIdTutor(@RequestHeader("idTutor") Long idTutor) {

List<Student> students = studentContactService.findStudentsByIdTutor(idTutor);

if (students.isEmpty()) {

return new ResponseEntity<>(NOT_FOUND);

}

return new ResponseEntity<>(students, OK);

}

@RequestMapping(method = GET, params = "firstName")

public ResponseEntity<List<Student>> findByName(@RequestHeader("idTutor") Long idTutor,

@RequestParam("firstName") String firstName) {

List<Student> students = studentContactService.findStudentsByIdTutorAndFirstName(idTutor, firstName);

if (students.isEmpty()) {

return new ResponseEntity<>(NOT_FOUND);

}

return new ResponseEntity<>(students, OK);

}

@RequestMapping(method = POST)

public ResponseEntity<Student> createStudent(@RequestHeader("idTutor") Long idTutor,

@RequestBody Student student,

UriComponentsBuilder builder) {

student.setIdTutor(idTutor);

Student saved = studentContactService.createOrUpdateStudent(student);

HttpHeaders headers = new HttpHeaders();

headers.setLocation(builder.path("/rest/student/{id}").buildAndExpand(saved.getId()).toUri());

return new ResponseEntity<>(headers, CREATED);

}

@RequestMapping(method = PUT, path = "/{id}")

public ResponseEntity<Student> updateStudent(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id,

@RequestBody Student student) {

Student found = studentContactService.findStudentById(id);

if (found == null || !found.getIdTutor().equals(idTutor)) {

return new ResponseEntity<>(NOT_FOUND);

}

student.setIdTutor(idTutor);

student.setId(id);

found = studentContactService.createOrUpdateStudent(student);

return new ResponseEntity<>(found, OK);

}

@RequestMapping(method = DELETE, path = "/{id}")

public ResponseEntity<Student> deleteStudent(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id) {

Student found = studentContactService.findStudentById(id);

if (found == null || !found.getIdTutor().equals(idTutor)) {

return new ResponseEntity<>(NOT_FOUND);

}

studentContactService.deleteStudent(id);

return new ResponseEntity<>(NO_CONTENT);

}

}

Листинг класса RestSubjectThemeController

package com.rep.core.restControllers;

import com.rep.core.dto.ThemeDto;

import com.rep.core.services.SubjectThemeService;

import com.rep.db.domain.Subject;

import com.rep.db.domain.Theme;

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

import org.springframework.http.HttpHeaders;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

import static org.springframework.http.HttpStatus.*;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@CrossOrigin

@RestController

@RequestMapping("/rest")

public class RestSubjectThemeController {

private final SubjectThemeService subjectThemeService;

@Autowired

public RestSubjectThemeController(SubjectThemeService subjectThemeService) {

this.subjectThemeService = subjectThemeService;

}

@RequestMapping(method = GET, path = "/theme/parent", params = {"idParent"})

public ResponseEntity<List<ThemeDto>> getThemesByIdParent(@RequestHeader("idTutor") Long idTutor,

@RequestParam("idParent") Long idParent) {

List<ThemeDto> themes = ThemeDto.of(subjectThemeService.findThemesByIdParent(idParent));

if (themes.isEmpty()) {

return new ResponseEntity<>(NO_CONTENT);

}

return new ResponseEntity<>(themes, OK);

}

@RequestMapping(method = GET, path = "/theme/tree/parent", params = {"idParent"})

public ResponseEntity<List<ThemeDto>> getTreeByIdParent(@RequestHeader("idTutor") Long idTutor,

@RequestParam("idParent") Long idParent) {

List<ThemeDto> themes = subjectThemeService.findTreeByIdParent(idParent);

if (themes.isEmpty()) {

return new ResponseEntity<>(NO_CONTENT);

}

return new ResponseEntity<>(themes, OK);

}

@RequestMapping(method = GET, path = "/subject/{idSubject}/theme")

public ResponseEntity<List<ThemeDto>> getThemesByIdSubject(@RequestHeader("idTutor") Long idTutor,

@PathVariable("idSubject") Long idSubject) {

List<ThemeDto> themes = ThemeDto.of(subjectThemeService.findThemesByIdSubject(idSubject));

if (themes.isEmpty()) {

return new ResponseEntity<>(NO_CONTENT);

}

return new ResponseEntity<>(themes, OK);

}

@RequestMapping(method = POST, path = "/subject")

public ResponseEntity<Subject> saveNewSubject(@RequestHeader("idTutor") Long idTutor,

@RequestBody Subject subject,

UriComponentsBuilder ucBuilder) {

subject.setIdTutor(idTutor);

Subject saved = subjectThemeService.createSubject(subject);

HttpHeaders headers = new HttpHeaders();

headers.setLocation(ucBuilder.path("/rest/theme/subject/{id}").buildAndExpand(saved.getIdTutor(), saved.getId()).toUri());

return new ResponseEntity<>(headers, CREATED);

}

@RequestMapping(method = POST, path = "/theme")

public ResponseEntity<Theme> saveNewTheme(@RequestHeader("idTutor") Long idTutor,

@RequestBody Theme theme,

UriComponentsBuilder ucBuilder) {

Theme saved = subjectThemeService.createTheme(theme);

HttpHeaders headers = new HttpHeaders();

headers.setLocation(ucBuilder.path("/rest/theme/{id}").buildAndExpand(saved.getId()).toUri());

return new ResponseEntity<>(theme, headers, CREATED);

}

@RequestMapping(method = DELETE, path = "/theme/{id}")

public ResponseEntity<Theme> deleteContactName(@RequestHeader("idTutor") Long idTutor,

@PathVariable("id") Long id) {

Theme found = subjectThemeService.findThemeById(id);

subjectThemeService.deleteThemeById(id);

return new ResponseEntity<>(NO_CONTENT);

}

}

Листинг класса RestTutorController

package com.rep.core.restControllers;

import com.rep.core.dto.TutorDto;

import com.rep.core.services.TutorService;

import com.rep.db.domain.Tutor;

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

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin

@RestController

@RequestMapping("/rest/tutor")

public class RestTutorController {

private TutorService tutorService;

@Autowired

RestTutorController(TutorService tutorService) {

this.tutorService = tutorService;

}

@RequestMapping(method = RequestMethod.GET)

public ResponseEntity<List<TutorDto>> listAllTutors() {

List<TutorDto> contacts = TutorDto.of(tutorService.listAllTutors());

if (contacts.isEmpty()) {

return new ResponseEntity<>(HttpStatus.NO_CONTENT);

}

return new ResponseEntity<>(contacts, HttpStatus.OK);

}

@RequestMapping(value = "/{id}", method = RequestMethod.GET)

public ResponseEntity<TutorDto> getTutor(@PathVariable("id") long id) {

Tutor tutor = tutorService.findById(id);

if (tutor == null) {

return new ResponseEntity<>(HttpStatus.NO_CONTENT);

}

TutorDto contactDto = TutorDto.of(tutor);

return new ResponseEntity<>(contactDto, HttpStatus.OK);

}

@RequestMapping(method = RequestMethod.POST)

public ResponseEntity<Tutor> createTutor(@RequestBody TutorDto tutorDto) {

Tutor saved = tutorService.createTutor(tutorDto);

return new ResponseEntity<>(saved, HttpStatus.CREATED);

}

@RequestMapping(value = "/{id}", method = RequestMethod.PUT)

public ResponseEntity<Tutor> updateTutor(@PathVariable("id") long id, @RequestBody Tutor tutor) {

Tutor current = tutorService.findById(id);

if (current == null) {

return new ResponseEntity<>(HttpStatus.NOT_FOUND);

}

current.setName(tutor.getName());

current.setAddress(tutor.getAddress());

tutorService.updateTutor(current);

return new ResponseEntity<>(current, HttpStatus.OK);

}

@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)

public ResponseEntity<Void> deleteTutor(@PathVariable("id") long id) {

Tutor current = tutorService.findById(id);

if (current == null) {

return new ResponseEntity<>(HttpStatus.NOT_FOUND);

}

tutorService.deleteTutor(id);

return new ResponseEntity<>(HttpStatus.NO_CONTENT);

}

}

Листинг класса DateUtil

package com.rep.core.common;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.*;

public class DateUtil {

private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

private final static SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

private final static SimpleDateFormat jsonFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

private final static List<Integer> months30 = Arrays.asList(3, 5, 8, 10);

private static boolean isLeap(Date date) {

int year = date.getYear() + 1900;

return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));

}

public static Date nextDate(Date date, int n) {

return new Date(date.getTime() + 1000L * 60 * 60 * 24 * n);

}

public static Date nextDay(Date date) {

return nextDate(date, 1);

}

public static Date nextWeek(Date date) {

return nextDate(date, 7);

}

public static Date nextMonth(Date date) {

if (date.getMonth() == 2) {

if (isLeap(date)) {

return nextDate(date, 29);

} else {

return nextDate(date, 28);

}

} else if (months30.contains(date.getMonth())) {

return nextDate(date, 30);

} else {

return nextDate(date, 31);

}

}

public static Date nextYear(Date date) {

if (isLeap(date)) {

return nextDate(date, 366);

} else {

return nextDate(date, 365);

}

}

public static boolean afterOrEqual(Date first, Date second) {

return first.after(second) || first.getTime() == second.getTime();

}

public static boolean beforeOrEqual(Date first, Date second) {

return first.before(second) || first.getTime() == second.getTime();

}

public static Date toDate(String stringDate) {

try {

return dateFormat.parse(stringDate);

} catch (ParseException e) {

return null;

}

}

public static String toString(Date date) {

return (date == null ? null : dateFormat.format(date));

}

}

Листинг класса ContactDto

package com.rep.core.dto;

import com.rep.db.domain.Contact;

import java.util.ArrayList;

import java.util.List;

public class ContactDto {

private Long id;

private Long idContactName;

private String contactName;

private String value;

public static ContactDto of(Contact contact) {

ContactDto result = new ContactDto();

result.setId(contact.getId());

result.setIdContactName(contact.getContactName().getId());

result.setContactName(contact.getContactName().getName());


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

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