attendance started

REL-BRANCH-ClubhelperModel-0.0.1
kre6513 5 years ago
parent f667b36d35
commit 8bb9156ac5
  1. 72
      src/main/java/de/kreth/clubhelper/model/controller/AttendanceController.java
  2. 50
      src/main/java/de/kreth/clubhelper/model/controller/GroupContoller.java
  3. 4
      src/main/java/de/kreth/clubhelper/model/controller/PersonController.java
  4. 1
      src/main/java/de/kreth/clubhelper/model/dao/AttendanceDao.java
  5. 239
      src/main/java/de/kreth/clubhelper/model/data/BaseEntity.java
  6. 74
      src/main/java/de/kreth/clubhelper/model/data/GroupDef.java
  7. 114
      src/test/java/de/kreth/clubhelper/model/LoadPersonsTest.java
  8. 98
      src/test/java/de/kreth/clubhelper/model/PersonControllerTest.java

@ -6,6 +6,7 @@ import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@ -15,41 +16,46 @@ import org.springframework.web.bind.annotation.ResponseBody;
import de.kreth.clubhelper.model.dao.AttendanceDao; import de.kreth.clubhelper.model.dao.AttendanceDao;
import de.kreth.clubhelper.model.dao.PersonDao; import de.kreth.clubhelper.model.dao.PersonDao;
import de.kreth.clubhelper.model.data.Attendance; import de.kreth.clubhelper.model.data.Attendance;
import de.kreth.clubhelper.model.data.Person;
@Controller @Controller
@RequestMapping("/attendance") @RequestMapping("/attendance")
@PreAuthorize("hasRole('trainer') or hasRole('admin')") @PreAuthorize("hasRole('trainer') or hasRole('admin')")
public class AttendanceController { public class AttendanceController
{
private AttendanceDao attendanceDao;
private PersonDao personDao; @Autowired
private AttendanceDao attendanceDao;
@Autowired
public AttendanceController(AttendanceDao attendanceDao, PersonDao personDao) { @Autowired
this.attendanceDao = attendanceDao; private PersonDao personDao;
this.personDao = personDao;
@PostMapping(value = "/on")
} @ResponseBody
public List<Attendance> getAttendencesOn(@RequestBody(required = false) Date date)
@PostMapping(value = "/on") {
@ResponseBody if (date == null) {
public List<Attendance> getAttendencesOn(@RequestBody(required = false) Date date) { date = new Date();
}
if (date == null) { return attendanceDao.findByOnDate(date);
date = new Date(); }
}
@PostMapping(value = "/for/{id}")
return attendanceDao.findByOnDate(date); @ResponseBody
} public Attendance post(@PathVariable("id") Integer id)
{
@PostMapping(value = "/for/{id}") Attendance att = new Attendance();
@ResponseBody att.setOnDate(new Date());
public Attendance post(@PathVariable("id") Integer id) { att.setPerson(personDao.findById(id).orElseThrow(() -> new RuntimeException("Person not found by id=" + id)));
attendanceDao.save(att);
Attendance att = new Attendance(); return att;
att.setOnDate(new Date()); }
att.setPerson(personDao.findById(id).orElseThrow(() -> new RuntimeException("Person not found by id=" + id)));
attendanceDao.save(att); @DeleteMapping("/{id}")
return att; public Attendance delete(@PathVariable("id") int personId, @RequestBody(required = true) Date onDate) {
} Person person = personDao.findById(personId).orElseThrow(() -> new RuntimeException("Person not found by id=" + personId));
Attendance attendance = attendanceDao.findByPersonAndOnDate(person, onDate);
attendanceDao.delete(attendance);
return attendance;
}
} }

@ -0,0 +1,50 @@
package de.kreth.clubhelper.model.controller;
import java.nio.charset.Charset;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import de.kreth.clubhelper.model.dao.GroupDao;
import de.kreth.clubhelper.model.data.GroupDef;
@RestController
@RequestMapping("/group")
@PreAuthorize("isAuthenticated()")
public class GroupContoller
{
@Autowired
private GroupDao groupDao;
@GetMapping
public List<GroupDef> allGroups() {
return StreamSupport.stream(groupDao.findAll().spliterator(), false)
.collect(Collectors.toList());
}
@GetMapping("/{id}")
public GroupDef getById(@PathVariable("id") int id) {
Supplier<HttpClientErrorException> supplier = () -> createNotFoundForId(id);
return groupDao.findById(id).orElseThrow(supplier);
}
private HttpClientErrorException createNotFoundForId(Integer id)
{
HttpHeaders headers = new HttpHeaders();
byte[] body = new byte[0];
Charset charset = Charset.forName("UTF-8");
HttpClientErrorException ex = HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Group not found by id=" + id, headers, body, charset);
return ex;
}
}

@ -16,6 +16,7 @@ import de.kreth.clubhelper.model.dao.PersonDao;
import de.kreth.clubhelper.model.data.Adress; import de.kreth.clubhelper.model.data.Adress;
import de.kreth.clubhelper.model.data.Contact; import de.kreth.clubhelper.model.data.Contact;
import de.kreth.clubhelper.model.data.Person; import de.kreth.clubhelper.model.data.Person;
import io.swagger.annotations.ApiOperation;
@Controller @Controller
@RequestMapping("/person") @RequestMapping("/person")
@ -24,13 +25,16 @@ public class PersonController
{ {
@Autowired @Autowired
private PersonDao personDao; private PersonDao personDao;
@Autowired @Autowired
private ContactController contactController; private ContactController contactController;
@Autowired @Autowired
private AdressController adressController; private AdressController adressController;
@GetMapping @GetMapping
@PreAuthorize("hasAnyRole('trainer', 'admin')") @PreAuthorize("hasAnyRole('trainer', 'admin')")
@ApiOperation("Get a list of all persons. Restricted to trainers and admins.")
public @ResponseBody Iterable<Person> getAll() public @ResponseBody Iterable<Person> getAll()
{ {
return personDao.findAll(); return personDao.findAll();

@ -14,4 +14,5 @@ public interface AttendanceDao extends CrudRepository<Attendance, Integer> {
List<Attendance> findByPerson(Person person); List<Attendance> findByPerson(Person person);
Attendance findByPersonAndOnDate(Person person, Date onDate);
} }

@ -10,119 +10,128 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
@MappedSuperclass @MappedSuperclass
public abstract class BaseEntity implements EntityAccessor { public abstract class BaseEntity implements EntityAccessor
{
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id; private int id;
@Temporal(TemporalType.TIMESTAMP)
@Temporal(TemporalType.TIMESTAMP) private Date changed;
private Date changed; @Temporal(TemporalType.TIMESTAMP)
private Date created;
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date created; private Date deleted;
@Temporal(TemporalType.TIMESTAMP) public Date getChanged()
private Date deleted; {
if (changed == null) {
public Date getChanged() { return null;
if (changed == null) { }
return null; return new Date(this.changed.getTime());
} }
return new Date(this.changed.getTime());
} @Override
public void setChanged(Date changed)
@Override {
public void setChanged(Date changed) { this.changed = new Date(changed.getTime());
this.changed = new Date(changed.getTime()); }
}
public Date getCreated()
public Date getCreated() { {
if (created == null) { if (created == null) {
return null; return null;
} }
return new Date(this.created.getTime()); return new Date(this.created.getTime());
} }
@Override @Override
public void setCreated(Date created) { public void setCreated(Date created)
this.created = new Date(created.getTime()); {
} this.created = new Date(created.getTime());
}
public Date getDeleted() {
if (deleted == null) { public Date getDeleted()
return null; {
} if (deleted == null) {
return new Date(this.deleted.getTime()); return null;
} }
return new Date(this.deleted.getTime());
public void setDeleted(Date deleted) { }
this.deleted = new Date(deleted.getTime());
} public void setDeleted(Date deleted)
{
@Override this.deleted = new Date(deleted.getTime());
public Integer getId() { }
return id;
} @Override
public Integer getId()
public void setId(int id) { {
this.id = id; return id;
} }
@Override public void setId(int id)
public boolean hasValidId() { {
return id > 0; this.id = id;
} }
@Override @Override
public int hashCode() { public boolean hasValidId()
final int prime = 31; {
int result = 1; return id > 0;
result = prime * result + ((changed == null) ? 0 : changed.hashCode()); }
result = prime * result + ((created == null) ? 0 : created.hashCode());
result = prime * result + ((deleted == null) ? 0 : deleted.hashCode()); @Override
result = prime * result + id; public int hashCode()
return result; {
} final int prime = 31;
int result = 1;
@Override result = prime * result + ((changed == null) ? 0 : changed.hashCode());
public boolean equals(Object obj) { result = prime * result + ((created == null) ? 0 : created.hashCode());
if (this == obj) { result = prime * result + ((deleted == null) ? 0 : deleted.hashCode());
return true; result = prime * result + id;
} return result;
if (obj == null) { }
return false;
} @Override
if (getClass() != obj.getClass()) { public boolean equals(Object obj)
return false; {
} if (this == obj) {
BaseEntity other = (BaseEntity) obj; return true;
if (deleted == null) { }
if (other.deleted != null) { if (obj == null) {
return false; return false;
} }
} else if (!deleted.equals(other.deleted)) { if (getClass() != obj.getClass()) {
return false; return false;
} }
if (id != other.id) { BaseEntity other = (BaseEntity) obj;
return false; if (deleted == null) {
} if (other.deleted != null) {
return true; return false;
} }
}
@Override else if (!deleted.equals(other.deleted)) {
public String toString() { return false;
StringBuilder stringBuilder = new StringBuilder(); }
stringBuilder.append("BaseEntity [id="); if (id != other.id) {
stringBuilder.append(id); return false;
stringBuilder.append(", changed="); }
stringBuilder.append(changed); return true;
if (deleted != null) { }
stringBuilder.append(", deleted=");
stringBuilder.append(deleted); @Override
} public String toString()
stringBuilder.append("]"); {
return stringBuilder.toString(); StringBuilder stringBuilder = new StringBuilder();
} stringBuilder.append("BaseEntity [id=");
stringBuilder.append(id);
stringBuilder.append(", changed=");
stringBuilder.append(changed);
if (deleted != null) {
stringBuilder.append(", deleted=");
stringBuilder.append(deleted);
}
stringBuilder.append("]");
return stringBuilder.toString();
}
} }

@ -10,45 +10,47 @@ import javax.persistence.Table;
/** /**
* The persistent class for the groupDef database table. * The persistent class for the groupDef database table.
*
*/ */
@Entity @Entity
@Table(name = "groupdef") @Table(name = "groupdef")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@NamedQuery(name = GroupDef.QUERY_FINDALL, query = "SELECT g FROM GroupDef g") @NamedQuery(name = GroupDef.QUERY_FINDALL, query = "SELECT g FROM GroupDef g")
public class GroupDef extends BaseEntity implements Serializable { public class GroupDef extends BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public final static String QUERY_FINDALL = "GroupDef.findAll";
public final static String QUERY_FINDALL = "GroupDef.findAll";
private String name;
private String name;
public String getName()
public String getName() { {
return name; return name;
} }
public void setName(String name) { public void setName(String name)
this.name = name; {
} this.name = name;
}
@Override
public int hashCode() { @Override
final int prime = 53; public int hashCode()
return prime * super.hashCode(); {
} final int prime = 53;
return prime * super.hashCode();
@Override }
public boolean equals(Object obj) {
if (this == obj) { @Override
return true; public boolean equals(Object obj)
} {
return super.equals(obj); if (this == obj) {
} return true;
}
@Override return super.equals(obj);
public String toString() { }
return "GroupDef [id=" + getId() + ", name=" + name + "]";
} @Override
public String toString()
{
return "GroupDef [id=" + getId() + ", name=" + name + "]";
}
} }

@ -10,7 +10,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.TestPropertySource;
import de.kreth.clubhelper.model.dao.GroupDao; import de.kreth.clubhelper.model.dao.GroupDao;
import de.kreth.clubhelper.model.dao.PersonDao; import de.kreth.clubhelper.model.dao.PersonDao;
@ -19,60 +19,60 @@ import de.kreth.clubhelper.model.data.GroupDef;
import de.kreth.clubhelper.model.data.Person; import de.kreth.clubhelper.model.data.Person;
@DataJpaTest() @DataJpaTest()
@Sql(scripts = "classpath:data.sql") //@Sql(scripts = "classpath:data.sql")
class LoadPersonsTest { @TestPropertySource(properties = {
"spring.jpa.hibernate.ddl-auto=none"
@Autowired })
PersonDao personDao; class LoadPersonsTest
{
@Autowired @Autowired
GroupDao groupDao; PersonDao personDao;
@Autowired
private GroupDef aktive; GroupDao groupDao;
private GroupDef trainer; private GroupDef aktive;
private GroupDef trainer;
private GroupDef competitor; private GroupDef competitor;
private GroupDef admin;
private GroupDef admin;
@BeforeEach
@BeforeEach void loadGroups()
void loadGroups() { {
aktive = groupDao.findById(1).get(); aktive = groupDao.findById(1).get();
trainer = groupDao.findById(3).get(); trainer = groupDao.findById(3).get();
competitor = groupDao.findById(7).get(); competitor = groupDao.findById(7).get();
admin = groupDao.findById(8).get(); admin = groupDao.findById(8).get();
assertNotNull(aktive); assertNotNull(aktive);
assertNotNull(trainer); assertNotNull(trainer);
assertNotNull(competitor); assertNotNull(competitor);
assertNotNull(admin); assertNotNull(admin);
} }
@Test @Test
void testLoadPerson1() { void testLoadPerson1()
Optional<Person> person1 = personDao.findById(1); {
assertTrue(person1.isPresent(), "Person with id=1 not found!"); Optional<Person> person1 = personDao.findById(1);
assertTrue(person1.get().isMember(trainer)); assertTrue(person1.isPresent(), "Person with id=1 not found!");
} assertTrue(person1.get().isMember(trainer));
}
@Test
void testLoadAll() { @Test
Iterable<Person> all = personDao.findAll(); void testLoadAll()
assertTrue(all.iterator().hasNext(), "No data found in Person"); {
} Iterable<Person> all = personDao.findAll();
assertTrue(all.iterator().hasNext(), "No data found in Person");
@Test }
void insertPerson() {
Person p = new Person(); @Test
p.setPrename("prename"); void insertPerson()
p.setSurname("surname"); {
p.setBirth(LocalDate.of(1981, 3, 3)); Person p = new Person();
p.setGender(Gender.MALE); p.setPrename("prename");
p.setSurname("surname");
personDao.save(p); p.setBirth(LocalDate.of(1981, 3, 3));
p.setGender(Gender.MALE);
assertNotNull(p.getId()); personDao.save(p);
personDao.delete(p); assertNotNull(p.getId());
} personDao.delete(p);
}
} }

@ -26,54 +26,58 @@ import de.kreth.clubhelper.model.dao.PersonDao;
import de.kreth.clubhelper.model.data.Gender; import de.kreth.clubhelper.model.data.Gender;
import de.kreth.clubhelper.model.data.Person; import de.kreth.clubhelper.model.data.Person;
@WebMvcTest(excludeAutoConfiguration = { DataSourceAutoConfiguration.class, JdbcRepositoriesAutoConfiguration.class, @WebMvcTest(excludeAutoConfiguration =
DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, {
SecurityAutoConfiguration.class }) DataSourceAutoConfiguration.class,
class PersonControllerTest { JdbcRepositoriesAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
JdbcTemplateAutoConfiguration.class,
SecurityAutoConfiguration.class
})
class PersonControllerTest
{
@Autowired
MockMvc mvc;
@MockBean
PersonDao personDao;
private Person p1;
private Person p2;
@Autowired @BeforeEach
MockMvc mvc; void initMocks()
{
p1 = new Person();
p1.setId(1);
p1.setPrename("prename");
p1.setSurname("surname");
p1.setBirth(LocalDate.of(2000, 1, 1));
p1.setGender(Gender.MALE);
p2 = new Person();
p2.setId(1);
p2.setPrename("prename");
p2.setSurname("surname");
p2.setBirth(LocalDate.of(2000, 1, 1));
p2.setGender(Gender.MALE);
when(personDao.findAll()).thenReturn(Arrays.asList(p1, p2));
when(personDao.findById(1)).thenReturn(Optional.of(p1));
when(personDao.findById(2)).thenReturn(Optional.of(p2));
}
@MockBean @Test
PersonDao personDao; void callAllPersons() throws Exception
{
private Person p1; String jsonListOfPersons = "[{\"id\":1,\"changed\":null,\"created\":null,\"deleted\":null,\"birth\":\"2000-01-01\",\"prename\":\"prename\",\"surname\":\"surname\",\"username\":null,\"password\":null,\"gender\":\"MALE\"},{\"id\":1,\"changed\":null,\"created\":null,\"deleted\":null,\"birth\":\"2000-01-01\",\"prename\":\"prename\",\"surname\":\"surname\",\"username\":null,\"password\":null,\"gender\":\"MALE\"}]";
mvc.perform(get("/person").accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)).andExpect(status().isOk())
private Person p2; .andExpect(content().string(jsonListOfPersons));
}
@BeforeEach
void initMocks() {
p1 = new Person();
p1.setId(1);
p1.setPrename("prename");
p1.setSurname("surname");
p1.setBirth(LocalDate.of(2000, 1, 1));
p1.setGender(Gender.MALE);
p2 = new Person();
p2.setId(1);
p2.setPrename("prename");
p2.setSurname("surname");
p2.setBirth(LocalDate.of(2000, 1, 1));
p2.setGender(Gender.MALE);
when(personDao.findAll()).thenReturn(Arrays.asList(p1, p2));
when(personDao.findById(1)).thenReturn(Optional.of(p1));
when(personDao.findById(2)).thenReturn(Optional.of(p2));
}
@Test
void callAllPersons() throws Exception {
String jsonListOfPersons = "[{\"id\":1,\"changed\":null,\"created\":null,\"deleted\":null,\"birth\":\"2000-01-01\",\"prename\":\"prename\",\"surname\":\"surname\",\"username\":null,\"password\":null,\"gender\":\"MALE\"},{\"id\":1,\"changed\":null,\"created\":null,\"deleted\":null,\"birth\":\"2000-01-01\",\"prename\":\"prename\",\"surname\":\"surname\",\"username\":null,\"password\":null,\"gender\":\"MALE\"}]";
mvc.perform(get("/person").accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML))
.andExpect(status().isOk()).andExpect(content().string(jsonListOfPersons));
}
@Test
void callPerson1() throws Exception {
String jsonListOfPersons = "{\"id\":1,\"changed\":null,\"created\":null,\"deleted\":null,\"birth\":\"2000-01-01\",\"prename\":\"prename\",\"surname\":\"surname\",\"username\":null,\"password\":null,\"gender\":\"MALE\"}";
mvc.perform(get("/person/1").accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML))
.andExpect(status().isOk()).andExpect(content().string(jsonListOfPersons));
}
@Test
void callPerson1() throws Exception
{
String jsonListOfPersons = "{\"id\":1,\"changed\":null,\"created\":null,\"deleted\":null,\"birth\":\"2000-01-01\",\"prename\":\"prename\",\"surname\":\"surname\",\"username\":null,\"password\":null,\"gender\":\"MALE\"}";
mvc.perform(get("/person/1").accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)).andExpect(status().isOk())
.andExpect(content().string(jsonListOfPersons));
}
} }

Loading…
Cancel
Save