Compare commits

..

6 Commits

7 changed files with 367 additions and 88 deletions

View File

@ -3,6 +3,9 @@ package com.vpr.server.controller;
import com.vpr.server.data.Event;
import com.vpr.server.data.User;
import com.vpr.server.data.UserEvent;
import com.vpr.server.dao.interfaces.EventDAO;
import com.vpr.server.json.JSONMapper;
import com.vpr.server.json.Validator;
import com.vpr.server.repository.EventRepository;
import com.vpr.server.repository.UserEventRepository;
import com.vpr.server.repository.UserRepository;
@ -11,10 +14,10 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.List;
@Controller
@RequestMapping(path = "/event")
@ -26,6 +29,9 @@ public class EventController {
@Autowired
private UserEventRepository userEventRepository;
@Autowired
private EventDAO eventDAO;
/******************
* POST-ENDPOINTS *
******************/
@ -33,68 +39,24 @@ public class EventController {
@PostMapping(path = "/add")
public @ResponseBody
ResponseEntity<String> addEvent(
@RequestParam Integer userId,
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam long userId,
@RequestParam String date,
@RequestParam String name,
@RequestParam String start,
@RequestParam String end,
@RequestParam Integer prority,
@RequestParam Integer priority,
@RequestParam Boolean isFullDay,
@RequestParam Boolean isPrivate
) {
String errorString = "";
Event event = new Event();
System.out.println(name.length() + ". name " + name);
if (name.length() > 3) {
event.setName(name);
} else {
System.out.println("NAME IST ZU KURZ");
return new ResponseEntity<>("Der Name ist zu kurz", HttpStatus.BAD_REQUEST);
User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
if (authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)) {
return new ResponseEntity<>("Du hast keine Rechte um den Termin zu erstellen", HttpStatus.UNAUTHORIZED);
}
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");
long ms = simpleDateFormat.parse(start).getTime();
event.setStart(new Time(ms));
} catch (Exception e) {
event.setStart(null);
}
ResponseEntity<String> BAD_REQUEST = createEventAndUserEvent(userId, date, name, start, end, priority, isFullDay, isPrivate);
if (BAD_REQUEST != null) return BAD_REQUEST;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");
long ms = simpleDateFormat.parse(end).getTime();
event.setEnd(new Time(ms));
} catch (Exception e) {
event.setEnd(null);
}
event.setPriority(prority);
event.setFullDay(isFullDay);
event.setPrivate(isPrivate);
UserEvent userEvent = new UserEvent();
try {
System.out.println("date " + date);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
userEvent.setDate(new java.sql.Date(simpleDateFormat.parse(date).getTime()));
} catch (Exception e) {
System.out.println("DATE FORMAT NOT CORRECT");
return new ResponseEntity<>("Datumformat nicht korrekt", HttpStatus.BAD_REQUEST);
}
userEvent.setEvent(event);
long uId = Long.valueOf(userId);
User user = userRepository.findById(uId);
userEvent.setUser(user);
System.out.println(userEvent);
System.out.println(user);
eventRepository.save(event);
userEventRepository.save(userEvent);
return new ResponseEntity<>("", HttpStatus.OK);
}
@ -102,36 +64,109 @@ public class EventController {
public @ResponseBody
ResponseEntity<String> delEvent(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam Integer eventId
@RequestParam long eventId,
@RequestParam long userId,
@RequestParam String date
) {
User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
if(authUser == null || authUser.isAdmin()){
return new ResponseEntity<>( "Du hast keine Rechte um den Termin zu löschen", HttpStatus.UNAUTHORIZED);
if (authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)) {
return new ResponseEntity<>("Du hast keine Rechte um den Termin zu löschen", HttpStatus.UNAUTHORIZED);
}
eventRepository.deleteUserEventsById(userId, eventId, date);
if(eventDAO.getAllEventsWithId(eventId).size() == 0){
eventRepository.deleteById(eventId);
}
eventRepository.deleteUserEventsById(Long.valueOf(eventId));
eventRepository.deleteById(Long.valueOf(eventId));
return new ResponseEntity<>("", HttpStatus.OK);
}
@PostMapping(path = "/all")
public @ResponseBody
Object[] getAllEvents(@RequestParam long userId) {
return eventRepository.findAllVisibleByUserId(userId);
ResponseEntity<String> getAllEvents(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam String startDate,
@RequestParam String endDate
) {
User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
if (authUser == null) {
return new ResponseEntity<>("Bitte erneut einloggen", HttpStatus.UNAUTHORIZED);
}
List<Event> eventList = eventDAO.getAllEventsInTimespan(authUser.getId(), startDate, endDate);
return new ResponseEntity<>(JSONMapper.ToJSON(eventList), HttpStatus.OK);
}
@PostMapping(path = "/edit")
public @ResponseBody
String editEvent(
@RequestParam Integer userId,
ResponseEntity<String> editEvent(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam Long eventId,
@RequestParam Long userId,
@RequestParam String date,
@RequestParam String name,
@RequestParam String start,
@RequestParam String end,
@RequestParam Integer prority,
@RequestParam Boolean isFullDay,
@RequestParam Boolean isPrivate
@RequestParam String newDate,
@RequestParam String newName,
@RequestParam String newStart,
@RequestParam String newEnd,
@RequestParam Integer newPriority,
@RequestParam Boolean newIsFullDay,
@RequestParam Boolean newIsPrivate
) {
return "";
User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
if (authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)) {
return new ResponseEntity<>("Du hast keine Rechte um den Termin zu bearbeiten", HttpStatus.UNAUTHORIZED);
}
List<Event> eventList = eventDAO.getAllEventsWithIdAndDate(userId, eventId, date);
if (eventList == null || eventList.size() == 0) {
return new ResponseEntity<>("Der Termin exestiert nicht in der Datenbank", HttpStatus.BAD_REQUEST);
}
if (eventList.size() > 1) {
return new ResponseEntity<>("Drr Termin ist doppelt vorhanden. (Um das zu lösen versuche den Termin zu löschen und erneut zu erstellen)", HttpStatus.BAD_REQUEST);
}
eventRepository.deleteUserEventsById(userId, eventId, date);
if(eventDAO.getAllEventsWithId(eventId).size() == 0){
eventRepository.deleteById(eventId);
}
ResponseEntity<String> BAD_REQUEST = createEventAndUserEvent(userId, newDate, newName, newStart, newEnd, newPriority, newIsFullDay, newIsPrivate);
if (BAD_REQUEST != null) return BAD_REQUEST;
return new ResponseEntity<>("", HttpStatus.OK);
}
private ResponseEntity<String> createEventAndUserEvent(long userId, String date, String name, String start, String end, Integer priority, Boolean isFullDay, Boolean isPrivate) {
User user = userRepository.findById(userId);
if(user == null){
return new ResponseEntity<>("UserId nicht korrekt", HttpStatus.BAD_REQUEST);
}
try {
Event event = new Event();
event.setName(Validator.ValidateEventName(name));
event.setStart(Validator.ValidateEventTime(start));
event.setEnd(Validator.ValidateEventTime(end));
event.setPriority(priority);
event.setFullDay(isFullDay);
event.setPrivate(isPrivate);
UserEvent userEvent = new UserEvent();
userEvent.setDate(Validator.ValidateEventDate(date));
userEvent.setEvent(event);
userEvent.setUser(user);
eventRepository.save(event);
userEventRepository.save(userEvent);
}catch (IllegalArgumentException exception){
return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
return null;
}
}

View File

@ -0,0 +1,48 @@
package com.vpr.server.dao.implementation;
import com.vpr.server.dao.interfaces.EventDAO;
import com.vpr.server.data.Event;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;
@Repository
@Transactional
public class EventDAOImplementation implements EventDAO {
@PersistenceContext
private EntityManager manager;
@Override
public List<Event> getAllEvents() {
return manager.createNamedQuery("getAllEvents", Event.class).getResultList();
}
@Override
public List<Event> getAllEventsWithId(long eventId) {
return manager.createNamedQuery("getAllEventsWithId", Event.class)
.setParameter("eventId", eventId)
.getResultList();
}
@Override
public List<Event> getAllEventsInTimespan(long userId, String startDate, String endDate) {
return manager.createNamedQuery("getAllEventsInTimespan", Event.class)
.setParameter("userId", userId)
.setParameter("startDate", startDate)
.setParameter("endDate", endDate)
.getResultList();
}
@Override
public List<Event> getAllEventsWithIdAndDate(long userId, long eventId, String date) {
return manager.createNamedQuery("getAllEventsWithIdAndDate", Event.class)
.setParameter("userId", userId)
.setParameter("eventId", eventId)
.setParameter("date", date)
.getResultList();
}
}

View File

@ -0,0 +1,16 @@
package com.vpr.server.dao.interfaces;
import com.vpr.server.data.Event;
import java.util.List;
public interface EventDAO {
List<Event> getAllEvents();
List<Event> getAllEventsInTimespan(long userId, String startDate, String endDate);
List<Event> getAllEventsWithIdAndDate(long userId, long eventId, String date);
List<Event> getAllEventsWithId(long eventId);
}

View File

@ -1,33 +1,73 @@
package com.vpr.server.data;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Time;
import java.util.List;
// @Entity creates a table out of this class with Hibernate
@Entity(name = "Event")
public class Event {
@Entity(name = "Event") // @Entity creates a table out of this class with Hibernate
@Table(name = "event")
@NamedNativeQueries({
@NamedNativeQuery(
name = "getAllEvents",
query = "SELECT * FROM event",
resultClass = Event.class
),
@NamedNativeQuery(
name = "getAllEventsInTimespan",
query = "SELECT * " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"WHERE (ue.user_id = :userId OR e.is_private = 0) " +
"AND ue.date > :startDate " +
"AND ue.date < :endDate " +
"ORDER BY ue.date, e.priority DESC, e.start",
resultClass = Event.class
),
@NamedNativeQuery(
name = "getAllEventsWithIdAndDate",
query = "SELECT * " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"WHERE ue.user_id = :userId " +
"AND ue.event_id = :eventId " +
"AND ue.date = :date",
resultClass = Event.class
),
@NamedNativeQuery(
name = "getAllEventsWithId",
query = "SELECT * " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"WHERE ue.event_id = :eventId",
resultClass = Event.class
)
})
public class Event implements Serializable {
// Generate the primary key
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name="name", nullable=false)
@Column(name = "name", nullable = false)
private String name;
@Column(name="priority", nullable=false)
@Column(name = "priority", nullable = false)
private Integer priority;
@Column(name="is_full_day", nullable=false)
@Column(name = "is_full_day", nullable = false)
private boolean isFullDay;
@Column(name="is_private", nullable=false)
@Column(name = "is_private", nullable = false)
private boolean isPrivate;
@Column(name="start")
@Column(name = "start")
private Time start;
@Column(name="end")
@Column(name = "end")
private Time end;
@OneToMany(mappedBy = "event")

View File

@ -0,0 +1,56 @@
package com.vpr.server.json;
import com.vpr.server.data.Event;
import com.vpr.server.data.UserEvent;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
public class JSONMapper {
public static List<String> ToJSON(Event event){
List<String> eventListJSON = new ArrayList<>();
for (UserEvent userEvent : event.getUserEvent()) {
String eventJSON = "{" +
"\"ownerId\": " + userEvent.getUser().getId() + ", " +
"\"ownerName\": \"" + userEvent.getUser().getForename() + " " + userEvent.getUser().getName() + "\", " +
"\"date\": \"" + userEvent.getDate() + "\", " +
"\"id\": " + event.getId() + "," +
"\"name\": \"" + event.getName() + "\"," +
"\"priority\": " + event.getPriority() + "," +
"\"fullDay\": " + event.isFullDay() + "," +
"\"private\": " + event.isPrivate() + "," +
"\"start\": " + ToJSON(event.getStart()) + "," +
"\"end\": " + ToJSON(event.getEnd()) +
"}";
eventListJSON.add(eventJSON);
}
return eventListJSON;
}
public static String ToJSON(List<Event> eventList){
StringBuilder eventListJSON = new StringBuilder();
for(Event event : eventList){
List<String> eventsJSON = ToJSON(event);
for(String eventJSON : eventsJSON){
eventListJSON.append(", ");
eventListJSON.append(eventJSON);
}
}
eventListJSON.delete(0, 2);
return "[" + eventListJSON + "]";
}
public static String ToJSON(Time time){
if(time == null){
return "null";
}
return "\"" + time + "\"";
}
}

View File

@ -0,0 +1,47 @@
package com.vpr.server.json;
import com.vpr.server.data.UserEvent;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.sql.Date;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Validator {
public static String ValidateEventName(String name) throws IllegalArgumentException {
if (name.length() < 3) {
System.out.println("NAME TO SHORT");
throw new IllegalArgumentException("Der Name ist zu kurz");
}
Pattern pattern = Pattern.compile("[A-Za-z\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df0-9 =!?+*/$.:,;_<>()-]*");
Matcher matcher = pattern.matcher(name);
if(!matcher.matches()){
System.out.println("NAME HAS ILLEGALCHARS");
throw new IllegalArgumentException("Der Name enthält nicht erlaubte Zeichen");
}
return name;
}
public static Time ValidateEventTime(String time) throws IllegalArgumentException {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");
long ms = simpleDateFormat.parse(time).getTime();
return new Time(ms);
} catch (Exception e) {
return null;
}
}
public static Date ValidateEventDate(String date) throws IllegalArgumentException {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return new Date(simpleDateFormat.parse(date).getTime());
} catch (Exception e) {
System.out.println("DATE FORMAT NOT CORRECT");
throw new IllegalArgumentException("Datumformat nicht korrekt");
}
}
}

View File

@ -1,17 +1,25 @@
package com.vpr.server.repository;
import com.vpr.server.data.Event;
import com.vpr.server.data.UserEvent;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import javax.persistence.ColumnResult;
import javax.persistence.ConstructorResult;
import javax.persistence.NamedNativeQuery;
import javax.persistence.SqlResultSetMapping;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
// This will be AUTO IMPLEMENTED by Spring into a Bean called eventRepository
// CRUD refers Create, Read, Update, Delete
public interface EventRepository extends CrudRepository<Event, Integer> {
@Query(value = "SELECT e.id AS eid, e.name AS ename, e.start, e.end, e.priority , e.is_full_day, " +
@Query(
value = "SELECT e.id AS eid, e.name AS ename, e.start, e.end, e.priority , e.is_full_day, " +
"ue.date, " +
"u.id AS uid, u.forename, u.name AS uname " +
"FROM event e " +
@ -21,27 +29,56 @@ public interface EventRepository extends CrudRepository<Event, Integer> {
"ON ue.user_id = u.id " +
"WHERE u.id = ?1 " +
"OR e.is_private = 0",
nativeQuery = true)
nativeQuery = true
)
Object[] findAllVisibleByUserId(long id);
@Query(value = "SELECT * " +
@Query(
value = "SELECT * " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"WHERE ue.user_id = ?1",
nativeQuery = true)
nativeQuery = true
)
Object[] findAllByUserId(long id);
@Query(
value = "SELECT ue.user_id as userId, ue.event_id as eventId, ue.date as date " +
"FROM event e " +
"INNER JOIN user_event ue " +
"ON e.id = ue.event_id " +
"WHERE ue.event_id = ?1 " +
"AND ue.user_id = ?2 " +
"AND ue.date = ?3",
nativeQuery = true
)
UserEventInterface findUserEventByEventIdUserIdAndDate(long eventId, long userId, String date);
interface UserEventInterface{
long getEventId();
long getUserId();
long getDate();
}
@Modifying
@Transactional
@Query(value = "DELETE ue FROM user_event ue WHERE ue.event_id = ?1",
nativeQuery = true)
void deleteUserEventsById(long id);
@Query(
value = "DELETE ue FROM user_event ue WHERE ue.event_id = :eventId AND ue.user_id = :userId AND ue.date = :date",
nativeQuery = true
)
void deleteUserEventsById(long userId, long eventId, String date);
@Modifying
@Transactional
@Query(value = "DELETE e FROM event e WHERE e.id = ?1",
nativeQuery = true)
@Query(
value = "DELETE e FROM event e WHERE e.id = ?1",
nativeQuery = true
)
void deleteById(long id);
//@Query(nativeQuery = true)
//List<Event> findEventsInDateRange(Long userId, String startDate, String endDate);
}