Hibernate Bugfixes, Refactoring

Database is cleared
master
Markus Kreth 7 years ago
parent 480b6b814d
commit 00463948db
  1. 41
      src/main/java/de/kreth/clubhelperbackend/google/calendar/CalendarAdapter.java
  2. 48
      src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/business/CalendarTaskRefresher.java
  3. 76
      src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/business/EventBusiness.java
  4. 44
      src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubEvent.java
  5. 25
      src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/GroupDef.java
  6. 60
      src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/Person.java
  7. 2
      src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/ui/MainUi.java
  8. 2
      src/main/resources/simplelogger.properties
  9. 20
      src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/business/CalendarTaskRefresherTest.java
  10. 90
      src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/AbstractDatabaseTest.java
  11. 3
      src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/ClubEventDaoTest.java
  12. 128
      src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/ClubEventDataTest.java
  13. 2
      src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/PersonDaoTest.java
  14. 9
      src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/ui/tests/TestConfiguration.java
  15. 30
      src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/ui/tests/VaadinClubhelperApplicationTests.java

@ -11,6 +11,8 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import org.springframework.stereotype.Component;
import com.google.api.client.util.DateTime; import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.model.Calendar; import com.google.api.services.calendar.model.Calendar;
import com.google.api.services.calendar.model.CalendarList; import com.google.api.services.calendar.model.CalendarList;
@ -21,6 +23,7 @@ import com.google.api.services.calendar.model.EventAttendee;
import de.kreth.clubhelperbackend.google.GoogleBaseAdapter; import de.kreth.clubhelperbackend.google.GoogleBaseAdapter;
import de.kreth.clubhelperbackend.google.calendar.CalendarResource.CalendarKonfig; import de.kreth.clubhelperbackend.google.calendar.CalendarResource.CalendarKonfig;
@Component
public class CalendarAdapter extends GoogleBaseAdapter { public class CalendarAdapter extends GoogleBaseAdapter {
com.google.api.services.calendar.Calendar service; com.google.api.services.calendar.Calendar service;
@ -40,9 +43,7 @@ public class CalendarAdapter extends GoogleBaseAdapter {
try { try {
super.checkRefreshToken(serverName); super.checkRefreshToken(serverName);
if (service == null) { if (service == null) {
service = createBuilder() service = createBuilder().setApplicationName(APPLICATION_NAME).build();
.setApplicationName(APPLICATION_NAME)
.build();
} }
} finally { } finally {
lock.unlock(); lock.unlock();
@ -54,13 +55,11 @@ public class CalendarAdapter extends GoogleBaseAdapter {
} }
} }
if (service == null) { if (service == null) {
throw new IllegalStateException( throw new IllegalStateException("Calendar Service not instanciated!");
"Calendar Service not instanciated!");
} }
} }
Calendar getCalendarBySummaryName(List<CalendarListEntry> items, Calendar getCalendarBySummaryName(List<CalendarListEntry> items, String calendarSummary) throws IOException {
String calendarSummary) throws IOException {
String calendarId = null; String calendarId = null;
for (CalendarListEntry e : items) { for (CalendarListEntry e : items) {
@ -70,15 +69,13 @@ public class CalendarAdapter extends GoogleBaseAdapter {
} }
} }
if (calendarId == null) { if (calendarId == null) {
throw new IllegalStateException( throw new IllegalStateException("Calendar " + calendarSummary + " not found!");
"Calendar " + calendarSummary + " not found!");
} }
return service.calendars().get(calendarId).execute(); return service.calendars().get(calendarId).execute();
} }
public List<Event> getAllEvents(String serverName) public List<Event> getAllEvents(String serverName) throws IOException, InterruptedException {
throws IOException, InterruptedException {
final List<Event> events = new ArrayList<>(); final List<Event> events = new ArrayList<>();
@ -88,8 +85,7 @@ public class CalendarAdapter extends GoogleBaseAdapter {
List<CalendarKonfig> configs = res.getConfigs(); List<CalendarKonfig> configs = res.getConfigs();
ExecutorService exec = Executors.newFixedThreadPool(configs.size()); ExecutorService exec = Executors.newFixedThreadPool(configs.size());
for (CalendarKonfig c : configs) { for (CalendarKonfig c : configs) {
exec.execute(new FetchEventsRunner(items, c.getName(), events, exec.execute(new FetchEventsRunner(items, c.getName(), events, oldest, c.getColor()));
oldest, c.getColor()));
} }
exec.shutdown(); exec.shutdown();
@ -113,16 +109,14 @@ public class CalendarAdapter extends GoogleBaseAdapter {
return oldestCal.getTimeInMillis(); return oldestCal.getTimeInMillis();
} }
List<CalendarListEntry> getCalendarList(String serverName) List<CalendarListEntry> getCalendarList(String serverName) throws IOException {
throws IOException {
checkRefreshToken(serverName); checkRefreshToken(serverName);
CalendarList calendarList; CalendarList calendarList;
try { try {
calendarList = service.calendarList().list().execute(); calendarList = service.calendarList().list().execute();
} catch (IOException e) { } catch (IOException e) {
if (log.isWarnEnabled()) { if (log.isWarnEnabled()) {
log.warn("Error fetching Calendar List, trying token refresh", log.warn("Error fetching Calendar List, trying token refresh", e);
e);
} }
refreshToken(); refreshToken();
if (log.isInfoEnabled()) { if (log.isInfoEnabled()) {
@ -140,8 +134,8 @@ public class CalendarAdapter extends GoogleBaseAdapter {
private List<CalendarListEntry> items; private List<CalendarListEntry> items;
private String summary; private String summary;
private FetchEventsRunner(List<CalendarListEntry> items, String summary, private FetchEventsRunner(List<CalendarListEntry> items, String summary, List<Event> events, long oldest,
List<Event> events, long oldest, String colorClass) { String colorClass) {
this.events = events; this.events = events;
this.oldest = oldest; this.oldest = oldest;
this.items = items; this.items = items;
@ -156,8 +150,8 @@ public class CalendarAdapter extends GoogleBaseAdapter {
log.debug("Fetching events of calendar \"{}\"", summary); log.debug("Fetching events of calendar \"{}\"", summary);
Calendar calendar = getCalendarBySummaryName(items, summary); Calendar calendar = getCalendarBySummaryName(items, summary);
DateTime timeMin = new DateTime(oldest); DateTime timeMin = new DateTime(oldest);
List<Event> eventItems = service.events().list(calendar.getId()) List<Event> eventItems = service.events().list(calendar.getId()).setTimeMin(timeMin).execute()
.setTimeMin(timeMin).execute().getItems(); .getItems();
eventItems.forEach(item -> item.set("colorClass", colorClass)); eventItems.forEach(item -> item.set("colorClass", colorClass));
events.addAll(eventItems); events.addAll(eventItems);
log.debug("Added {} Events for \"{}\"", eventItems.size(), summary); log.debug("Added {} Events for \"{}\"", eventItems.size(), summary);
@ -169,9 +163,8 @@ public class CalendarAdapter extends GoogleBaseAdapter {
} }
static Event createDefaultEvent(String summary) { static Event createDefaultEvent(String summary) {
Event ev = new Event().setGuestsCanInviteOthers(false) Event ev = new Event().setGuestsCanInviteOthers(false).setGuestsCanModify(false)
.setGuestsCanModify(false).setGuestsCanSeeOtherGuests(true) .setGuestsCanSeeOtherGuests(true).setSummary(summary);
.setSummary(summary);
List<EventAttendee> attendees = new ArrayList<>(); List<EventAttendee> attendees = new ArrayList<>();
ev.setAttendees(attendees); ev.setAttendees(attendees);
return ev; return ev;

@ -1,5 +1,8 @@
package de.kreth.vaadin.clubhelper.vaadinclubhelper.business; package de.kreth.vaadin.clubhelper.vaadinclubhelper.business;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.validation.ConstraintViolationException; import javax.validation.ConstraintViolationException;
@ -11,6 +14,7 @@ import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import de.kreth.clubhelperbackend.google.calendar.CalendarAdapter;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.ClubEventDao; import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.ClubEventDao;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent;
@ -25,17 +29,18 @@ public class CalendarTaskRefresher {
@Autowired @Autowired
ClubEventDao dao; ClubEventDao dao;
@Autowired @Autowired
EventBusiness eventBusiness; CalendarAdapter calendarAdapter;
@Scheduled(fixedDelay = RATE) @Scheduled(fixedDelay = RATE)
public void synchronizeCalendarTasks() { public void synchronizeCalendarTasks() {
if (skip) { if (skip) {
return; return;
} }
List<ClubEvent> events = eventBusiness.loadEvents(null, true);
for (ClubEvent e : events) { List<ClubEvent> list = loadEventsFromGoogle();
for (ClubEvent e : list) {
if (dao.get(e.getId()) == null) { if (dao.get(e.getId()) == null) {
try { try {
log.trace("try inserting {}", e); log.trace("try inserting {}", e);
@ -52,11 +57,42 @@ public class CalendarTaskRefresher {
} }
} }
public List<ClubEvent> loadEventsFromGoogle() {
log.debug("Loading events from Google Calendar");
List<ClubEvent> list = new ArrayList<>();
try (FileExporter ex = FileExporter.builder(log).setFileName("google_events.json").setAppend(false).disable()
.build()) {
String remoteHost = "localhost";
List<com.google.api.services.calendar.model.Event> events = calendarAdapter.getAllEvents(remoteHost);
for (com.google.api.services.calendar.model.Event ev : events) {
ex.writeLine(ev.toPrettyString());
if ("cancelled".equals(ev.getStatus())) {
log.debug("Cancelled: {}", ev.getSummary());
} else {
list.add(ClubEvent.parse(ev));
}
}
} catch (GeneralSecurityException | IOException | InterruptedException e) {
log.error("Error loading events from google.", e);
} catch (Exception e1) {
log.warn("Error closing " + FileExporter.class.getSimpleName(), e1);
}
return list;
}
public void setDao(ClubEventDao dao) { public void setDao(ClubEventDao dao) {
this.dao = dao; this.dao = dao;
} }
public void setEventBusiness(EventBusiness eventBusiness) { public void setCalendarAdapter(CalendarAdapter calendarAdapter) {
this.eventBusiness = eventBusiness; this.calendarAdapter = calendarAdapter;
} }
} }

@ -1,9 +1,5 @@
package de.kreth.vaadin.clubhelper.vaadinclubhelper.business; package de.kreth.vaadin.clubhelper.vaadinclubhelper.business;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -12,9 +8,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.vaadin.server.VaadinRequest;
import de.kreth.clubhelperbackend.google.calendar.CalendarAdapter;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.ClubEventDao; import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.ClubEventDao;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Person; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Person;
@ -23,79 +16,40 @@ import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Person;
public class EventBusiness { public class EventBusiness {
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired @Autowired
ClubEventDao dao; ClubEventDao dao;
private ClubEvent current; private ClubEvent current;
public List<ClubEvent> loadEvents(VaadinRequest request) { public synchronized List<ClubEvent> loadEvents() {
return loadEvents(request, false);
}
public synchronized List<ClubEvent> loadEvents(VaadinRequest request,
boolean forceRefresh) {
if (forceRefresh == false) {
List<ClubEvent> list = dao.listAll();
log.trace("Returning events from database: {}", list);
return list;
}
log.debug(
"Loading events from Google Calendar, forceRefresh={}",
forceRefresh);
List<ClubEvent> list = new ArrayList<>();
try (FileExporter ex = FileExporter.builder(log).setFileName("google_events.json").setAppend(false).disable().build()) {
String remoteHost = "localhost"; List<ClubEvent> list = dao.listAll();
CalendarAdapter adapter = new CalendarAdapter(); log.trace("Returning events from database: {}", list);
List<com.google.api.services.calendar.model.Event> events = adapter return list;
.getAllEvents(remoteHost);
for (com.google.api.services.calendar.model.Event ev : events) {
ex.writeLine(ev.toPrettyString());
if ("cancelled".equals(ev.getStatus())) {
log.debug("Cancelled: {}", ev.getSummary());
} else {
list.add(ClubEvent.parse(ev));
}
}
} catch (GeneralSecurityException | IOException
| InterruptedException e) {
log.error("Error loading events from google.", e);
} catch (Exception e1) {
log.warn("Error closing " + FileExporter.class.getSimpleName(), e1);
}
return Collections.unmodifiableList(list);
} }
public ClubEvent getCurrent() { public ClubEvent getCurrent() {
return current; return current;
} }
public void setSelected(ClubEvent ev) { public void setSelected(ClubEvent ev) {
this.current = ev; this.current = ev;
} }
public void changePersons(Set<Person> selected) { public void changePersons(Set<Person> selected) {
if (current != null) { if (current != null) {
for (Person p : selected) {
Set<Person> store = current.getPersons(); current.add(p);
if (store != null) { }
log.debug("adding to existing person set."); try {
store.addAll(selected); dao.update(current);
} else { log.info("Updated {}, {} with participants: {}", current.getCaption(), current.getStart(), selected);
log.debug("setting persons to event without person set."); } catch (Exception e) {
current.setPersons(selected); log.error("Unable to update Event {}, {}, {} with participants: {}", current.getId(),
current.getCaption(), current.getStart(), selected, e);
} }
dao.update(current);
log.info("Updated {} with participants: {}", current, selected);
} }
} }
} }

@ -6,6 +6,7 @@ import java.time.ZonedDateTime;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.persistence.Transient; import javax.persistence.Transient;
@ -44,6 +45,7 @@ public class ClubEvent extends BasicItem {
this.organizerDisplayName = organizerDisplayName; this.organizerDisplayName = organizerDisplayName;
} }
@Override
public String getCaption() { public String getCaption() {
return super.getCaption(); return super.getCaption();
} }
@ -88,24 +90,37 @@ public class ClubEvent extends BasicItem {
public Set<Person> getPersons() { public Set<Person> getPersons() {
return persons; return persons;
} }
public void setPersons(Set<Person> persons) { public void setPersons(Set<Person> persons) {
this.persons = persons; this.persons = persons;
} }
public void add(Person p) {
if (this.persons == null) {
this.persons = new HashSet<>();
}
if (this.persons.contains(p)) {
return;
}
this.persons.add(p);
p.add(this);
}
public void remove(Person person) {
persons.remove(person);
person.remove(this);
}
@Transient @Transient
public String toDisplayString() { public String toDisplayString() {
return "ClubEvent [Caption=" + getCaption() + ", Start=" + getStart() return "ClubEvent [Caption=" + getCaption() + ", Start=" + getStart() + ", location=" + location + "]";
+ ", location=" + location + "]";
} }
@Override @Override
public String toString() { public String toString() {
return "ClubEvent [id=" + id + ", getCaption()=" + getCaption() + ", iCalUID=" + iCalUID + ", location=" return "ClubEvent [id=" + id + ", getCaption()=" + getCaption() + ", iCalUID=" + iCalUID + ", location="
+ location + ", organizerDisplayName=" + organizerDisplayName + location + ", organizerDisplayName=" + organizerDisplayName + ", getDescription()=" + getDescription()
+ ", getDescription()=" + ", getEnd()=" + getEnd() + ", getStart()=" + getStart() + ", isAllDay()=" + isAllDay() + "]";
+ getDescription() + ", getEnd()=" + getEnd() + ", getStart()="
+ getStart() + ", isAllDay()=" + isAllDay() + "]";
} }
public static ClubEvent parse(Event ev) { public static ClubEvent parse(Event ev) {
@ -204,14 +219,11 @@ public class ClubEvent extends BasicItem {
return null; return null;
} }
public static Date adjustExcludedEndDate( public static Date adjustExcludedEndDate(com.google.api.services.calendar.model.Event e) {
com.google.api.services.calendar.model.Event e) {
if (e.isEndTimeUnspecified() == false) { if (e.isEndTimeUnspecified() == false) {
EventDateTime end = e.getEnd(); EventDateTime end = e.getEnd();
GregorianCalendar calendar = new GregorianCalendar(); GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(end.getDate() != null calendar.setTimeInMillis(end.getDate() != null ? end.getDate().getValue() : end.getDateTime().getValue());
? end.getDate().getValue()
: end.getDateTime().getValue());
if (startIsDateOnly(e)) { if (startIsDateOnly(e)) {
calendar.add(Calendar.DAY_OF_MONTH, -1); calendar.add(Calendar.DAY_OF_MONTH, -1);
} }
@ -220,15 +232,13 @@ public class ClubEvent extends BasicItem {
return null; return null;
} }
public static boolean startIsDateOnly( public static boolean startIsDateOnly(com.google.api.services.calendar.model.Event e) {
com.google.api.services.calendar.model.Event e) {
EventDateTime start = e.getStart(); EventDateTime start = e.getStart();
if (start == null) { if (start == null) {
start = e.getOriginalStartTime(); start = e.getOriginalStartTime();
} }
return (start.getDate() != null || (start.getDateTime() != null return (start.getDate() != null || (start.getDateTime() != null && start.getDateTime().isDateOnly()));
&& start.getDateTime().isDateOnly()));
} }
} }

@ -7,8 +7,6 @@ import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.Inheritance; import javax.persistence.Inheritance;
import javax.persistence.InheritanceType; import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany; import javax.persistence.ManyToMany;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table; import javax.persistence.Table;
@ -29,11 +27,8 @@ public class GroupDef extends BaseEntity implements Serializable {
private String name; private String name;
@ManyToMany(fetch=FetchType.LAZY) @ManyToMany(fetch = FetchType.LAZY, mappedBy = "groups")
@JoinTable (name = "persongroup", private List<Person> persongroups;
joinColumns = { @JoinColumn(name = "group_id") },
inverseJoinColumns = { @JoinColumn(name = "person_id") })
private List<Persongroup> persongroups;
public GroupDef() { public GroupDef() {
} }
@ -46,26 +41,20 @@ public class GroupDef extends BaseEntity implements Serializable {
this.name = name; this.name = name;
} }
public List<Persongroup> getPersongroups() { public List<Person> getPersongroups() {
return this.persongroups; return this.persongroups;
} }
public void setPersongroups(List<Persongroup> persongroups) { public void setPersongroups(List<Person> persongroups) {
this.persongroups = persongroups; this.persongroups = persongroups;
} }
public Persongroup addPersongroup(Persongroup persongroup) { public void addPersongroup(Person persongroup) {
getPersongroups().add(persongroup); persongroups.add(persongroup);
persongroup.setGroupDef(this);
return persongroup;
} }
public Persongroup removePersongroup(Persongroup persongroup) { public void removePersongroup(Person persongroup) {
getPersongroups().remove(persongroup); getPersongroups().remove(persongroup);
persongroup.setGroupDef(null);
return persongroup;
} }
@Override @Override

@ -2,11 +2,20 @@ package de.kreth.vaadin.clubhelper.vaadinclubhelper.data;
import java.io.Serializable; import java.io.Serializable;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Date; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import javax.persistence.*; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/** /**
* The persistent class for the person database table. * The persistent class for the person database table.
@ -45,10 +54,9 @@ public class Person extends BaseEntity implements Serializable {
private List<Contact> contacts; private List<Contact> contacts;
// bi-directional many-to-many association to Persongroup // bi-directional many-to-many association to Persongroup
@ManyToMany(fetch=FetchType.EAGER) @ManyToMany(fetch = FetchType.EAGER)
@JoinTable (name = "persongroup", @JoinTable(name = "persongroup", joinColumns = { @JoinColumn(name = "person_id") }, inverseJoinColumns = {
joinColumns = { @JoinColumn(name = "person_id") }, @JoinColumn(name = "group_id") })
inverseJoinColumns = { @JoinColumn(name = "group_id") })
private List<GroupDef> groups; private List<GroupDef> groups;
// bi-directional many-to-one association to Relative // bi-directional many-to-one association to Relative
@ -63,14 +71,9 @@ public class Person extends BaseEntity implements Serializable {
@OneToMany(mappedBy = "person") @OneToMany(mappedBy = "person")
private List<Startpaesse> startpaesses; private List<Startpaesse> startpaesses;
@ManyToMany(cascade = { CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE, CascadeType.DETACH }, fetch = FetchType.LAZY) @ManyToMany(fetch = FetchType.EAGER, mappedBy = "persons")
@JoinTable(
name = "clubevent_has_person",
joinColumns = { @JoinColumn(name = "person_id") },
inverseJoinColumns = { @JoinColumn(name = "clubevent_id") }
)
private Set<ClubEvent> events; private Set<ClubEvent> events;
public LocalDate getBirth() { public LocalDate getBirth() {
return birth; return birth;
} }
@ -111,6 +114,37 @@ public class Person extends BaseEntity implements Serializable {
this.username = username; this.username = username;
} }
public List<GroupDef> getGroups() {
return groups;
}
public void setGroups(List<GroupDef> groups) {
this.groups = groups;
}
public void add(GroupDef group) {
}
public Set<ClubEvent> getEvents() {
return events;
}
public void setEvents(Set<ClubEvent> events) {
this.events = events;
}
public void add(ClubEvent ev) {
if (this.events == null) {
this.events = new HashSet<>();
}
this.events.add(ev);
}
public void remove(ClubEvent clubEvent) {
events.remove(clubEvent);
}
public List<Adress> getAdresses() { public List<Adress> getAdresses() {
return this.adresses; return this.adresses;
} }

@ -79,7 +79,7 @@ public class MainUi extends UI {
ExecutorService exec = Executors.newSingleThreadExecutor(); ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(() -> { exec.execute(() -> {
final List<ClubEvent> events = eventBusiness.loadEvents(request); final List<ClubEvent> events = eventBusiness.loadEvents();
LOGGER.info("Loaded events: {}", events); LOGGER.info("Loaded events: {}", events);
final UI ui = calendar.getUI(); final UI ui = calendar.getUI();
ui.access(() -> { ui.access(() -> {

@ -1,4 +1,4 @@
org.slf4j.simpleLogger.defaultLogLevel = warn org.slf4j.simpleLogger.defaultLogLevel = debug
log4j.logger.de.kreth.vaadin.clubhelper=trace log4j.logger.de.kreth.vaadin.clubhelper=trace
log4j.logger.org.hibernate.type=warn log4j.logger.org.hibernate.type=warn
log4j.logger.org.jboss.logging=warn log4j.logger.org.jboss.logging=warn

@ -1,10 +1,10 @@
package de.kreth.vaadin.clubhelper.vaadinclubhelper.business; package de.kreth.vaadin.clubhelper.vaadinclubhelper.business;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import de.kreth.clubhelperbackend.google.calendar.CalendarAdapter;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.ClubEventDao; import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.ClubEventDao;
class CalendarTaskRefresherTest { class CalendarTaskRefresherTest {
@ -19,28 +20,29 @@ class CalendarTaskRefresherTest {
@Mock @Mock
private ClubEventDao dao; private ClubEventDao dao;
@Mock @Mock
private EventBusiness eventBusiness; private CalendarAdapter calendarAdapter;
@BeforeEach @BeforeEach
void setUp() throws Exception { void setUp() throws Exception {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
when(eventBusiness.loadEvents(any(), anyBoolean())).thenReturn(Collections.emptyList()); when(calendarAdapter.getAllEvents(anyString())).thenReturn(Collections.emptyList());
} }
@Test @Test
void testSkip() { void testSkip() throws IOException, InterruptedException {
System.setProperty(CalendarTaskRefresher.SKIP_EVENT_UPDATE, Boolean.FALSE.toString());
CalendarTaskRefresher r = new CalendarTaskRefresher(); CalendarTaskRefresher r = new CalendarTaskRefresher();
r.setDao(dao); r.setDao(dao);
r.setEventBusiness(eventBusiness); r.setCalendarAdapter(calendarAdapter);
r.synchronizeCalendarTasks(); r.synchronizeCalendarTasks();
verify(eventBusiness).loadEvents(any(), anyBoolean()); verify(calendarAdapter).getAllEvents(anyString());
System.setProperty(CalendarTaskRefresher.SKIP_EVENT_UPDATE, Boolean.TRUE.toString()); System.setProperty(CalendarTaskRefresher.SKIP_EVENT_UPDATE, Boolean.TRUE.toString());
r = new CalendarTaskRefresher(); r = new CalendarTaskRefresher();
r.setDao(dao); r.setDao(dao);
r.setEventBusiness(eventBusiness); r.setCalendarAdapter(calendarAdapter);
r.synchronizeCalendarTasks(); r.synchronizeCalendarTasks();
verify(eventBusiness).loadEvents(any(), anyBoolean()); verify(calendarAdapter).getAllEvents(anyString());
} }
} }

@ -1,8 +1,18 @@
package de.kreth.vaadin.clubhelper.vaadinclubhelper.dao; package de.kreth.vaadin.clubhelper.vaadinclubhelper.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.EntityTransaction;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Adress; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Adress;
@ -19,11 +29,11 @@ import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Version;
public abstract class AbstractDatabaseTest { public abstract class AbstractDatabaseTest {
protected SessionFactory sessionFactory; protected static SessionFactory sessionFactory;
protected Session session; protected static Session session;
@BeforeEach @BeforeAll
public void setUp() throws Exception { public static void setUpDatabase() throws Exception {
// setup the session factory // setup the session factory
Configuration configuration = createConfig(); Configuration configuration = createConfig();
@ -33,7 +43,7 @@ public abstract class AbstractDatabaseTest {
} }
public Configuration createConfig() { public static Configuration createConfig() {
Configuration configuration = new Configuration(); Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Adress.class); configuration.addAnnotatedClass(Adress.class);
configuration.addAnnotatedClass(Attendance.class); configuration.addAnnotatedClass(Attendance.class);
@ -46,7 +56,7 @@ public abstract class AbstractDatabaseTest {
configuration.addAnnotatedClass(Startpaesse.class); configuration.addAnnotatedClass(Startpaesse.class);
configuration.addAnnotatedClass(StartpassStartrechte.class); configuration.addAnnotatedClass(StartpassStartrechte.class);
configuration.addAnnotatedClass(Version.class); configuration.addAnnotatedClass(Version.class);
configuration.addInputStream(getClass().getResourceAsStream("/schema/ClubEvent.hbm.xml")); configuration.addInputStream(AbstractDatabaseTest.class.getResourceAsStream("/schema/ClubEvent.hbm.xml"));
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
@ -55,4 +65,72 @@ public abstract class AbstractDatabaseTest {
return configuration; return configuration;
} }
public enum DB_TYPE {
MYSQL("SET @@foreign_key_checks = 0", "SET @@foreign_key_checks = 1"),
H2("SET REFERENTIAL_INTEGRITY FALSE", "SET REFERENTIAL_INTEGRITY TRUE");
private DB_TYPE(String disableReferentialIntegrety, String enableReferentialIntegrety) {
this.disableReferentialIntegrety = disableReferentialIntegrety;
this.enableReferentialIntegrety = enableReferentialIntegrety;
}
final String disableReferentialIntegrety;
final String enableReferentialIntegrety;
}
@BeforeEach
public void cleanH2Database() {
session.doWork(conn -> {
AbstractDatabaseTest.cleanDatabase(conn, DB_TYPE.H2);
});
}
public static void cleanDatabase(Connection connection, DB_TYPE type) throws SQLException {
String TABLE_NAME = "TABLE_NAME";
String[] TABLE_TYPES = { "TABLE" };
Set<String> tableNames = new HashSet<>();
try (ResultSet tables = connection.getMetaData().getTables(null, null, null, TABLE_TYPES)) {
while (tables.next()) {
tableNames.add(tables.getString(TABLE_NAME));
}
}
try (Statement stm = connection.createStatement()) {
stm.execute(type.disableReferentialIntegrety);
try {
for (String tableName : tableNames) {
try {
stm.executeUpdate("TRUNCATE TABLE " + tableName);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
} finally {
stm.execute(type.enableReferentialIntegrety);
}
}
if (connection.getAutoCommit() == false) {
connection.commit();
}
}
/**
* executes the given runnable within a jpa Transaction.
*
* @param r
*/
protected void transactional(Runnable r) {
EntityTransaction tx = session.getTransaction();
tx.begin();
try {
r.run();
tx.commit();
} catch (Exception e) {
tx.rollback();
throw e;
}
}
} }

@ -27,9 +27,6 @@ public class ClubEventDaoTest extends AbstractDatabaseTest {
@Autowired @Autowired
private ClubEventDao dao; private ClubEventDao dao;
// @Autowired
// private TestEntityManager entityManager;
@Test @Test
public void storeEvent() { public void storeEvent() {
dao.save(creteEvent()); dao.save(creteEvent());

@ -5,9 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.ZoneId; import java.time.ZoneId;
@ -16,11 +14,9 @@ import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger;
import org.hibernate.IdentifierLoadAccess; import org.hibernate.IdentifierLoadAccess;
import org.hibernate.Transaction;
import org.hibernate.jdbc.Work;
import org.hibernate.query.Query; import org.hibernate.query.Query;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -31,32 +27,33 @@ import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Person;
public class ClubEventDataTest extends AbstractDatabaseTest { public class ClubEventDataTest extends AbstractDatabaseTest {
private static final AtomicInteger counter = new AtomicInteger();
public Person testInsertPerson() { public Person testInsertPerson() {
Person p = new Person(); Person p = new Person();
p.setPrename("prename"); p.setPrename("prename");
p.setSurname("surname"); p.setSurname("surname");
p.setBirth(LocalDate.now()); p.setBirth(LocalDate.now());
Transaction tx = session.beginTransaction();
session.save(p); transactional(() -> session.save(p));
tx.commit();
return p; return p;
} }
public List<Person> insertPersons(int count) { public List<Person> insertPersons(int count) {
List<Person> inserted = new ArrayList<>(); final List<Person> inserted = new ArrayList<>();
Transaction tx = session.beginTransaction(); transactional(() -> {
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
Person p = new Person(); Person p = new Person();
p.setPrename("prename_" + i); p.setPrename("prename_" + i);
p.setSurname("surname_" + i); p.setSurname("surname_" + i);
p.setBirth(LocalDate.now()); p.setBirth(LocalDate.now());
session.save(p); session.save(p);
inserted.add(p); inserted.add(p);
} }
tx.commit(); });
for (Person p : inserted) { for (Person p : inserted) {
assertTrue(p.getId() > 0, "not saved: " + p); assertTrue(p.getId() > 0, "not saved: " + p);
} }
@ -64,22 +61,10 @@ public class ClubEventDataTest extends AbstractDatabaseTest {
} }
@Test @Test
public void testInsertEvent() { public void testSaveAndSelectEvent() {
ClubEvent ev = creteEvent();
Transaction tx = session.beginTransaction();
session.save(ev);
tx.commit();
}
@Test
public void testSelectEvents() {
ClubEvent ev = creteEvent(); ClubEvent ev = creteEvent();
Transaction tx = session.beginTransaction(); transactional(() -> session.save(ev));
session.save(ev);
tx.commit();
Query<ClubEvent> query = session.createNamedQuery("ClubEvent.findAll", ClubEvent.class); Query<ClubEvent> query = session.createNamedQuery("ClubEvent.findAll", ClubEvent.class);
List<ClubEvent> result = query.list(); List<ClubEvent> result = query.list();
assertEquals(1, result.size()); assertEquals(1, result.size());
@ -98,9 +83,7 @@ public class ClubEventDataTest extends AbstractDatabaseTest {
} }
persons.add(person); persons.add(person);
Transaction tx = session.beginTransaction(); transactional(() -> session.save(ev));
session.save(ev);
tx.commit();
List<ClubeventHasPerson> loadEventPersons = loadEventPersons(); List<ClubeventHasPerson> loadEventPersons = loadEventPersons();
assertFalse(loadEventPersons.isEmpty()); assertFalse(loadEventPersons.isEmpty());
@ -111,14 +94,12 @@ public class ClubEventDataTest extends AbstractDatabaseTest {
} }
private List<ClubeventHasPerson> loadEventPersons() { private List<ClubeventHasPerson> loadEventPersons() {
final AtomicBoolean finishedWork = new AtomicBoolean(false);
List<ClubeventHasPerson> link = new ArrayList<>();
session.doWork(new Work() { return session.doReturningWork(conn -> {
List<ClubeventHasPerson> link = new ArrayList<>();
@Override try (Statement stm = conn.createStatement()) {
public void execute(Connection connection) throws SQLException {
Statement stm = connection.createStatement();
ResultSet rs = stm.executeQuery("select * from clubevent_has_person"); ResultSet rs = stm.executeQuery("select * from clubevent_has_person");
while (rs.next()) { while (rs.next()) {
ClubeventHasPerson ep = new ClubeventHasPerson(); ClubeventHasPerson ep = new ClubeventHasPerson();
@ -127,21 +108,18 @@ public class ClubEventDataTest extends AbstractDatabaseTest {
ep.setPersonId(rs.getInt("person_id")); ep.setPersonId(rs.getInt("person_id"));
link.add(ep); link.add(ep);
} }
finishedWork.set(true);
} }
return link;
}); });
assertTrue(finishedWork.get());
return link;
} }
@Test @Test
public void changeEventsPersons() { public void changeEventsPersons() {
ClubEvent ev = creteEvent(); ClubEvent ev = creteEvent();
Transaction tx = session.beginTransaction(); transactional(() -> session.save(ev));
session.save(ev);
tx.commit();
Person person = testInsertPerson(); Person person = testInsertPerson();
@ -151,9 +129,7 @@ public class ClubEventDataTest extends AbstractDatabaseTest {
person2.setSurname(person.getSurname() + "_2"); person2.setSurname(person.getSurname() + "_2");
person2.setBirth(LocalDate.now()); person2.setBirth(LocalDate.now());
tx = session.beginTransaction(); transactional(() -> session.save(person2));
session.save(person2);
tx.commit();
IdentifierLoadAccess<ClubEvent> idLoadAccess = session.byId(ClubEvent.class); IdentifierLoadAccess<ClubEvent> idLoadAccess = session.byId(ClubEvent.class);
ClubEvent loaded = idLoadAccess.load(ev.getId()); ClubEvent loaded = idLoadAccess.load(ev.getId());
@ -163,14 +139,11 @@ public class ClubEventDataTest extends AbstractDatabaseTest {
} }
loaded.getPersons().add(person); loaded.getPersons().add(person);
tx = session.beginTransaction(); transactional(() -> session.update(ev));
session.update(ev);
tx.commit();
loaded.getPersons().add(person2); loaded.getPersons().add(person2);
tx = session.beginTransaction(); transactional(() -> session.update(ev));
session.update(ev);
tx.commit();
List<ClubeventHasPerson> entries = loadEventPersons(); List<ClubeventHasPerson> entries = loadEventPersons();
assertEquals(2, entries.size()); assertEquals(2, entries.size());
} }
@ -178,41 +151,34 @@ public class ClubEventDataTest extends AbstractDatabaseTest {
@Test @Test
public void testChangeEventParticipantsRapidly() { public void testChangeEventParticipantsRapidly() {
ClubEvent ev = creteEvent(); final ClubEvent created = creteEvent();
ev.setPersons(new HashSet<>()); transactional(() -> {
Transaction tx = session.beginTransaction(); session.save(created);
session.save(ev); });
tx.commit();
ev = session.byId(ClubEvent.class).load(ev.getId()); final ClubEvent ev = session.byId(ClubEvent.class).load(created.getId());
List<Person> persons = insertPersons(6); List<Person> persons = insertPersons(6);
for (Person p : persons) { for (Person p : persons) {
ev.getPersons().add(p); ev.add(p);
tx = session.beginTransaction(); transactional(() -> session.merge(ev));
session.merge(ev);
tx.commit();
} }
ev.getPersons().remove(persons.get(2)); ev.remove(persons.get(2));
tx = session.beginTransaction(); transactional(() -> session.merge(ev));
session.merge(ev);
tx.commit(); ev.remove(persons.get(4));
ev.getPersons().remove(persons.get(4)); transactional(() -> session.merge(ev));
tx = session.beginTransaction();
session.merge(ev);
tx.commit();
ev.getPersons().add(persons.get(2)); ev.getPersons().add(persons.get(2));
ev.getPersons().add(persons.get(4)); ev.getPersons().add(persons.get(4));
tx = session.beginTransaction(); transactional(() -> session.merge(ev));
session.merge(ev);
tx.commit();
List<ClubeventHasPerson> result = loadEventPersons(); List<ClubeventHasPerson> result = loadEventPersons();
assertEquals(6, result.size()); assertEquals(6, result.size());
} }
private ClubEvent creteEvent() { private ClubEvent creteEvent() {
ClubEvent ev = ClubEventBuilder.builder().withId("id").withAllDay(true).withCaption("caption") ClubEvent ev = ClubEventBuilder.builder().withId("id_" + counter.getAndIncrement()).withAllDay(true)
.withDescription("description") .withCaption("caption").withDescription("description")
.withStart(ZonedDateTime.of(2018, 8, 13, 0, 0, 0, 0, ZoneId.systemDefault())) .withStart(ZonedDateTime.of(2018, 8, 13, 0, 0, 0, 0, ZoneId.systemDefault()))
.withEnd(ZonedDateTime.of(2018, 8, 13, 0, 0, 0, 0, ZoneId.systemDefault())).withiCalUID("iCalUID") .withEnd(ZonedDateTime.of(2018, 8, 13, 0, 0, 0, 0, ZoneId.systemDefault())).withiCalUID("iCalUID")
.withOrganizerDisplayName("organizerDisplayName").build(); .withOrganizerDisplayName("organizerDisplayName").build();

@ -17,10 +17,8 @@ public class PersonDaoTest extends AbstractDatabaseTest {
private PersonDaoImpl personDao; private PersonDaoImpl personDao;
private Person person; private Person person;
@Override
@BeforeEach @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
super.setUp();
personDao = new PersonDaoImpl(); personDao = new PersonDaoImpl();
personDao.em = session; personDao.em = session;
person = new Person(); person = new Person();

@ -1,11 +1,15 @@
package de.kreth.vaadin.clubhelper.vaadinclubhelper.ui.tests; package de.kreth.vaadin.clubhelper.vaadinclubhelper.ui.tests;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import de.kreth.clubhelperbackend.google.calendar.CalendarAdapter;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Adress; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Adress;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Attendance; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Attendance;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Contact; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Contact;
@ -32,6 +36,11 @@ public class TestConfiguration {
} }
@Bean
public CalendarAdapter getCalendarAdapter() throws GeneralSecurityException, IOException {
return new CalendarAdapter();
}
public org.hibernate.cfg.Configuration createConfig() { public org.hibernate.cfg.Configuration createConfig() {
org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration(); org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration();
configuration.addAnnotatedClass(Adress.class); configuration.addAnnotatedClass(Adress.class);

@ -6,18 +6,12 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import java.awt.GraphicsEnvironment; import java.awt.GraphicsEnvironment;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.YearMonth; import java.time.YearMonth;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.time.format.TextStyle; import java.time.format.TextStyle;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@ -43,6 +37,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.web.server.LocalServerPort;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.business.CalendarTaskRefresher; import de.kreth.vaadin.clubhelper.vaadinclubhelper.business.CalendarTaskRefresher;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.AbstractDatabaseTest;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEventBuilder; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEventBuilder;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.GroupDef; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.GroupDef;
@ -174,28 +169,7 @@ public class VaadinClubhelperApplicationTests {
org.hibernate.Session session = (Session) em; org.hibernate.Session session = (Session) em;
session.doWork(connection -> { session.doWork(connection -> {
AbstractDatabaseTest.cleanDatabase(connection, AbstractDatabaseTest.DB_TYPE.H2);
String TABLE_NAME = "TABLE_NAME";
String[] TABLE_TYPES = { "TABLE" };
ResultSet tables = connection.getMetaData().getTables(null, null, null, TABLE_TYPES);
Set<String> tableNames = new HashSet<>();
while (tables.next()) {
tableNames.add(tables.getString(TABLE_NAME));
}
tables.close();
Statement stm = connection.createStatement();
while (tableNames.size() > 0) {
for (Iterator<String> iter = tableNames.iterator(); iter.hasNext();) {
String tableName = iter.next();
try {
stm.executeUpdate("DELETE FROM " + tableName);
iter.remove();
} catch (SQLException e) {
System.out.println("Must be later: " + tableName);
}
}
}
}); });
} }

Loading…
Cancel
Save