Added refactored /event/ endpoints

This commit is contained in:
Marc Beyer 2022-01-18 22:27:57 +01:00
parent 35e7350962
commit 154617ce88
7 changed files with 211 additions and 93 deletions

View File

@ -4,7 +4,8 @@ import com.vpr.server.data.Event;
import com.vpr.server.data.User; import com.vpr.server.data.User;
import com.vpr.server.data.UserEvent; import com.vpr.server.data.UserEvent;
import com.vpr.server.dao.interfaces.EventDAO; import com.vpr.server.dao.interfaces.EventDAO;
import com.vpr.server.json.EventJSONMapper; import com.vpr.server.json.JSONMapper;
import com.vpr.server.json.Validator;
import com.vpr.server.repository.EventRepository; import com.vpr.server.repository.EventRepository;
import com.vpr.server.repository.UserEventRepository; import com.vpr.server.repository.UserEventRepository;
import com.vpr.server.repository.UserRepository; import com.vpr.server.repository.UserRepository;
@ -38,68 +39,24 @@ public class EventController {
@PostMapping(path = "/add") @PostMapping(path = "/add")
public @ResponseBody public @ResponseBody
ResponseEntity<String> addEvent( ResponseEntity<String> addEvent(
@RequestParam Integer userId, @RequestHeader("Authorization") String authorizationHeader,
@RequestParam long userId,
@RequestParam String date, @RequestParam String date,
@RequestParam String name, @RequestParam String name,
@RequestParam String start, @RequestParam String start,
@RequestParam String end, @RequestParam String end,
@RequestParam Integer prority, @RequestParam Integer priority,
@RequestParam Boolean isFullDay, @RequestParam Boolean isFullDay,
@RequestParam Boolean isPrivate @RequestParam Boolean isPrivate
) { ) {
String errorString = ""; User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
if (authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)) {
Event event = new Event(); return new ResponseEntity<>("Du hast keine Rechte um den Termin zu erstellen", HttpStatus.UNAUTHORIZED);
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);
} }
try { ResponseEntity<String> BAD_REQUEST = createEventAndUserEvent(userId, date, name, start, end, priority, isFullDay, isPrivate);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm"); if (BAD_REQUEST != null) return BAD_REQUEST;
long ms = simpleDateFormat.parse(start).getTime();
event.setStart(new Time(ms));
} catch (Exception e) {
event.setStart(null);
}
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); return new ResponseEntity<>("", HttpStatus.OK);
} }
@ -111,52 +68,105 @@ public class EventController {
@RequestParam long userId, @RequestParam long userId,
@RequestParam String date @RequestParam String date
) { ) {
System.out.println("authorizationHeader " + authorizationHeader);
User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]); User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
if(authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)){ if (authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)) {
return new ResponseEntity<>( "Du hast keine Rechte um den Termin zu löschen", HttpStatus.UNAUTHORIZED); return new ResponseEntity<>("Du hast keine Rechte um den Termin zu löschen", HttpStatus.UNAUTHORIZED);
} }
EventRepository.UserEventInterface userEvent = eventRepository.findUserEventByEventIdUserIdAndDate(eventId, authUser.getId(), date); eventRepository.deleteUserEventsById(userId, eventId, date);
if(eventDAO.getAllEventsWithId(eventId).size() == 0){
//Optional<Event> event = eventRepository.findById(eventId); eventRepository.deleteById(eventId);
if (userEvent == null){
return new ResponseEntity<>( "Der Termin exestiert nicht", HttpStatus.BAD_REQUEST);
} }
return new ResponseEntity<>( "Der Termin exestiert", HttpStatus.OK);
/*
eventRepository.deleteUserEventsById(eventId);
eventRepository.deleteById(eventId);
return new ResponseEntity<>("", HttpStatus.OK); return new ResponseEntity<>("", HttpStatus.OK);
*/
} }
/*
@PostMapping(path = "/all") @PostMapping(path = "/all")
public @ResponseBody public @ResponseBody
List<Event> getAllEvents( ResponseEntity<String> getAllEvents(
@RequestParam long userId, @RequestHeader("Authorization") String authorizationHeader,
@RequestParam String startDate, @RequestParam String startDate,
@RequestParam String endDate @RequestParam String endDate
) { ) {
return eventRepository.findEventsInDateRange(userId, startDate, 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") @PostMapping(path = "/edit")
public @ResponseBody public @ResponseBody
String editEvent( ResponseEntity<String> editEvent(
@RequestHeader("Authorization") String authorizationHeader,
@RequestParam Long eventId, @RequestParam Long eventId,
@RequestParam Long userId, @RequestParam Long userId,
@RequestParam String date @RequestParam String date,
@RequestParam String newDate,
@RequestParam String newName,
@RequestParam String newStart,
@RequestParam String newEnd,
@RequestParam Integer newPriority,
@RequestParam Boolean newIsFullDay,
@RequestParam Boolean newIsPrivate
) { ) {
//EventRepository.UserEventInterface userEvent = eventRepository.findUserEventByEventIdUserIdAndDate(eventId, userId, date); User authUser = userRepository.findByToken(authorizationHeader.split("\\s")[1]);
//List<Event> userEvent = eventRepository.findByNativeQuery(); if (authUser == null || (!authUser.isAdmin() && authUser.getId() != userId)) {
List<Event> eventList = eventDAO.getAllEvents(); return new ResponseEntity<>("Du hast keine Rechte um den Termin zu bearbeiten", HttpStatus.UNAUTHORIZED);
}
return EventJSONMapper.ToJSON(eventList); 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

@ -20,4 +20,29 @@ public class EventDAOImplementation implements EventDAO {
public List<Event> getAllEvents() { public List<Event> getAllEvents() {
return manager.createNamedQuery("getAllEvents", Event.class).getResultList(); 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

@ -5,5 +5,12 @@ import com.vpr.server.data.Event;
import java.util.List; import java.util.List;
public interface EventDAO { public interface EventDAO {
List<Event> getAllEvents(); 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

@ -38,6 +38,37 @@ import java.util.List;
name = "getAllEvents", name = "getAllEvents",
query = "SELECT * FROM event", query = "SELECT * FROM event",
resultClass = Event.class 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",
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 { public class Event implements Serializable {

View File

@ -7,25 +7,23 @@ import java.sql.Time;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class EventJSONMapper { public class JSONMapper {
public static List<String> ToJSON(Event event){ public static List<String> ToJSON(Event event){
List<String> eventListJSON = new ArrayList<>(); List<String> eventListJSON = new ArrayList<>();
for (UserEvent userEvent : event.getUserEvent()) { for (UserEvent userEvent : event.getUserEvent()) {
String eventJSON = "{" + String eventJSON = "{" +
"\"ownerId\": " + "\"ownerId\": " + userEvent.getUser().getId() + ", " +
userEvent.getUser().getId() + "\"ownerName\": \"" + userEvent.getUser().getForename() + " " + userEvent.getUser().getName() + "\", " +
", \"ownerId\": \"" + "\"date\": \"" + userEvent.getDate() + "\", " +
userEvent.getUser().getName() + "\"id\": " + event.getId() + "," +
", \"date\": \"" + "\"name\": \"" + event.getName() + "\"," +
userEvent.getDate() + "\"priority\": " + event.getPriority() + "," +
"\", " + "\"isFullDay\": " + event.isFullDay() + "," +
"\"id\": " + event.getId() + "," + "\"isPrivate\": " + event.isPrivate() + "," +
"\"name\": \"" + event.getName() + "\"," + "\"start\": " + ToJSON(event.getStart()) + "," +
"\"priority\": " + event.getPriority() + "," + "\"end\": " + ToJSON(event.getEnd()) +
"\"start\": " + ToJSON(event.getStart()) + "," +
"\"end\": " + ToJSON(event.getEnd()) +
"}"; "}";
eventListJSON.add(eventJSON); eventListJSON.add(eventJSON);

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

@ -65,10 +65,10 @@ public interface EventRepository extends CrudRepository<Event, Integer> {
@Modifying @Modifying
@Transactional @Transactional
@Query( @Query(
value = "DELETE ue FROM user_event ue WHERE ue.event_id = ?1", value = "DELETE ue FROM user_event ue WHERE ue.event_id = :eventId AND ue.user_id = :userId AND ue.date = :date",
nativeQuery = true nativeQuery = true
) )
void deleteUserEventsById(long id); void deleteUserEventsById(long userId, long eventId, String date);
@Modifying @Modifying