Commit 715d68ad by Tuukka Kivilahti

Merge branch 'lectures' into user_selectable_groups

Conflicts:
	code/MoyaBeans/ejbModule/fi/codecrew/moya/beans/BootstrapBean.java
	code/MoyaDatabase/src/fi/codecrew/moya/model/Role.java
2 parents 8755c1e7 ef91de45
Showing with 2195 additions and 529 deletions
......@@ -8,3 +8,4 @@
.metadata
/code/*/target/
/code/*/test-output/
moya-git.properties
......@@ -2,7 +2,6 @@ package fi.codecrew.moya.beans;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.annotation.security.DeclareRoles;
......@@ -10,13 +9,10 @@ import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import fi.codecrew.moya.facade.ActionLogFacade;
import fi.codecrew.moya.facade.ActionLogMessageTagFacade;
import fi.codecrew.moya.beans.ActionLogBeanLocal;
import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.beans.RoleBeanLocal;
import fi.codecrew.moya.enums.ActionLogMessageState;
import fi.codecrew.moya.enums.apps.ContentPermission;
import fi.codecrew.moya.facade.ActionLogFacade;
import fi.codecrew.moya.facade.ActionLogMessageTagFacade;
import fi.codecrew.moya.model.ActionLogMessage;
import fi.codecrew.moya.model.ActionLogMessageResponse;
import fi.codecrew.moya.model.ActionLogMessageTag;
......@@ -39,10 +35,10 @@ public class ActionLogBean implements ActionLogBeanLocal {
@EJB
private PermissionBeanLocal permissionBean;
@EJB
private ActionLogMessageTagFacade actionLogMessageTagFacade;
@EJB
private EventBean eventBean;
......@@ -54,7 +50,7 @@ public class ActionLogBean implements ActionLogBeanLocal {
@RolesAllowed(ContentPermission.S_MANAGE_ACTIONLOG)
public void createActionLogEvent(String message, boolean isTask) {
ArrayList<ActionLogMessageTag> almts = resolveTags(message);
ActionLogMessage alm = new ActionLogMessage();
if (isTask) {
alm.setState(ActionLogMessageState.NEW);
......@@ -66,7 +62,7 @@ public class ActionLogBean implements ActionLogBeanLocal {
alm.setUser(permissionBean.getCurrentUser());
alm.setLanEvent(permissionBean.getCurrentUser().getEvent());
alm.setTags(almts);
actionLogFacade.saveToActionLog(alm);
}
......@@ -75,11 +71,11 @@ public class ActionLogBean implements ActionLogBeanLocal {
public List<ActionLogMessage> getAllActionLogEvents() {
return actionLogFacade.getAllSortedByTimestamp(permissionBean.getCurrentUser().getEvent());
}
@Override
@RolesAllowed(ContentPermission.S_MANAGE_ACTIONLOG)
public List<ActionLogMessage> getAllActionLogEventsByFilter(List<ActionLogMessageTag> filterTags) {
if(filterTags.size() == 0)
if (filterTags.size() == 0)
return actionLogFacade.getAllSortedByTimestamp(permissionBean.getCurrentUser().getEvent());
else
return actionLogFacade.getAllSortedByTimestampFiltered(permissionBean.getCurrentUser().getEvent(), filterTags);
......@@ -92,10 +88,11 @@ public class ActionLogBean implements ActionLogBeanLocal {
@RolesAllowed(ContentPermission.S_MANAGE_ACTIONLOG)
public List<ActionLogMessageResponse> getActionLogMessageResponses(ActionLogMessage alm) {
if(!alm.getLanEvent().equals(permissionBean.getCurrentUser().getEvent())) return null;
if (!alm.getLanEvent().equals(permissionBean.getCurrentUser().getEvent()))
return null;
return actionLogFacade.getActionLogMessageResponses(alm);
}
@Override
@RolesAllowed(ContentPermission.S_MANAGE_ACTIONLOG)
public List<ActionLogMessageTag> getAllTags() {
......@@ -104,8 +101,9 @@ public class ActionLogBean implements ActionLogBeanLocal {
@RolesAllowed(ContentPermission.S_MANAGE_ACTIONLOG)
public void addActionLogMessageResponse(ActionLogMessage alm, String message, ActionLogMessageState state) {
if(!alm.getLanEvent().equals(permissionBean.getCurrentUser().getEvent())) return;
if (!alm.getLanEvent().equals(permissionBean.getCurrentUser().getEvent()))
return;
if (alm.getState() != state && state != null) {
alm = actionLogFacade.merge(alm);
alm.setState(state);
......@@ -124,67 +122,68 @@ public class ActionLogBean implements ActionLogBeanLocal {
@RolesAllowed(ContentPermission.S_MANAGE_ACTIONLOG)
public ActionLogMessage find(Integer id) {
ActionLogMessage alm = actionLogFacade.find(id);
if(!alm.getLanEvent().equals(permissionBean.getCurrentUser().getEvent())) return null;
else return alm;
if (!alm.getLanEvent().equals(permissionBean.getCurrentUser().getEvent()))
return null;
else
return alm;
}
private ArrayList<ActionLogMessageTag> resolveTags(String message) {
ArrayList<ActionLogMessageTag> almts = new ArrayList<>();
StringBuilder sb = null;
boolean rflag = false;
char ch;
for(int i=0; i < message.length(); i++) {
if(rflag) {
if((ch = message.charAt(i)) != ' ') {
for (int i = 0; i < message.length(); i++) {
if (rflag) {
if ((ch = message.charAt(i)) != ' ') {
sb.append(ch);
} else {
if(sb.length() > 0) {
if (sb.length() > 0) {
ActionLogMessageTag almt = getActionLogMessageTagByString(sb.toString());
if(!almts.contains(almt)) {
if (!almts.contains(almt)) {
almts.add(almt);
}
}
rflag = false;
sb = null;
}
} else if(!rflag) {
if(message.charAt(i) == '#') {
rflag=true;
sb=new StringBuilder();
} else if (!rflag) {
if (message.charAt(i) == '#') {
rflag = true;
sb = new StringBuilder();
}
}
}
if(sb != null && sb.length() > 0) {
if (sb != null && sb.length() > 0) {
ActionLogMessageTag almt = getActionLogMessageTagByString(sb.toString());
if(!almts.contains(almt)) {
if (!almts.contains(almt)) {
almts.add(almt);
}
}
return almts;
}
@Override
@RolesAllowed(ContentPermission.S_MANAGE_ACTIONLOG)
public ActionLogMessageTag getActionLogMessageTagByString(String s) {
s = s.toLowerCase();
ActionLogMessageTag almt = null;
if((almt = actionLogMessageTagFacade.findByTagStringInEvent(s, eventBean.getCurrentEvent())) == null) {
ActionLogMessageTag almt = null;
if ((almt = actionLogMessageTagFacade.findByTagStringInEvent(s, eventBean.getCurrentEvent())) == null) {
almt = new ActionLogMessageTag();
almt.setEvent(eventBean.getCurrentEvent());
almt.setTag(s);
almt = actionLogMessageTagFacade.create(almt);
System.out.println("creating tag: "+s);
actionLogMessageTagFacade.create(almt);
System.out.println("creating tag: " + s);
return almt;
} else {
System.out.println("re-using tag: "+s);
System.out.println("re-using tag: " + s);
return almt;
}
}
}
\ No newline at end of file
......@@ -79,6 +79,7 @@ public class BootstrapBean implements BootstrapBeanLocal {
dbUpdates.add(new String[] {
"alter table compos add hidden boolean default false not null"
});
dbUpdates.add(alterTables("ADD COLUMN meta json",
"account_events",
"actionlog_message_responses",
......@@ -149,7 +150,60 @@ public class BootstrapBean implements BootstrapBeanLocal {
"user_images",
"user_notes",
"users"));
dbUpdates.add(new String[] { "ALTER TABLE roles ADD COLUMN select_childrens_count integer DEFAULT null;" });
dbUpdates.add(new String[]{"CREATE TABLE network_associations (id SERIAL NOT NULL, create_time TIMESTAMPTZ NOT NULL, ip TEXT, mac TEXT, meta TEXT, modify_time TIMESTAMPTZ NOT NULL, status TEXT NOT NULL, event INTEGER, event_user INTEGER, place INTEGER, PRIMARY KEY (id))"});
dbUpdates.add(new String[] {
"CREATE TABLE card_text_data (id SERIAL NOT NULL, font_name TEXT NOT NULL, font_style INTEGER NOT NULL, size INTEGER NOT NULL, text TEXT, text_alignment TEXT NOT NULL, card_text_data_type TEXT NOT NULL, x INTEGER NOT NULL, y INTEGER NOT NULL, z_index INTEGER NOT NULL, PRIMARY KEY (id));"
});
dbUpdates.add(new String[] {
"CREATE TABLE card_object_data (id SERIAL NOT NULL, card_object_data_type TEXT NOT NULL, size INTEGER NOT NULL, x INTEGER NOT NULL, y INTEGER NOT NULL, z_index INTEGER NOT NULL, PRIMARY KEY (id));"
});
dbUpdates.add(new String[] {
"ALTER TABLE card_text_data ADD COLUMN card_templates_id integer REFERENCES card_templates(id) DEFAULT null;",
"ALTER TABLE card_object_data ADD COLUMN card_templates_id integer REFERENCES card_templates(id) DEFAULT null;"
});
dbUpdates.add(alterTables("ADD COLUMN meta json",
"card_text_data",
"card_object_data"
));
dbUpdates.add(new String[] {
"ALTER TABLE card_text_data ADD COLUMN font_color_r integer DEFAULT 0;",
"ALTER TABLE card_text_data ADD COLUMN font_color_g integer DEFAULT 0;",
"ALTER TABLE card_text_data ADD COLUMN font_color_b integer DEFAULT 0;"
});
dbUpdates.add(new String[] {
"ALTER TABLE card_text_data ALTER COLUMN size TYPE numeric(5,2);",
"ALTER TABLE card_object_data ALTER COLUMN size TYPE numeric(5,2);"
});
dbUpdates.add(new String[] {
"ALTER TABLE card_text_data DROP COLUMN font_style;",
"ALTER TABLE card_text_data ADD COLUMN font_style TEXT NOT NULL DEFAULT 'PLAIN';"
});
dbUpdates.add(new String[] {
"ALTER TABLE event_log RENAME log_id TO id;"
});
dbUpdates.add(new String[] {
"ALTER TABLE network_associations ALTER COLUMN meta TYPE json USING (meta::json);"
});
dbUpdates.add(new String[] {"CREATE TABLE lecture_groups (id SERIAL NOT NULL, event_id integer NOT NULL, description TEXT, name TEXT, select_count INTEGER, meta json, PRIMARY KEY (id))",
"CREATE TABLE lectures (id SERIAL NOT NULL, description TEXT, hours numeric(10,2), max_participants_count INTEGER, name TEXT, start_time TIMESTAMPTZ, lecture_group_id INTEGER, meta json, PRIMARY KEY (id))",
"CREATE TABLE lecture_roles (role_id INTEGER NOT NULL, lecture_id INTEGER NOT NULL, PRIMARY KEY (role_id, lecture_id))",
"CREATE TABLE lecture_participants (eventuser_id INTEGER NOT NULL, lecture_id INTEGER NOT NULL, PRIMARY KEY (eventuser_id, lecture_id))",
"ALTER TABLE lectures ADD CONSTRAINT FK_lectures_lecture_group_id FOREIGN KEY (lecture_group_id) REFERENCES lecture_groups (id)",
"ALTER TABLE lecture_roles ADD CONSTRAINT FK_lecture_roles_lecture_id FOREIGN KEY (lecture_id) REFERENCES lectures (id)",
"ALTER TABLE lecture_roles ADD CONSTRAINT FK_lecture_roles_role_id FOREIGN KEY (role_id) REFERENCES roles (id)",
"ALTER TABLE lecture_participants ADD CONSTRAINT FK_lecture_participants_eventuser_id FOREIGN KEY (eventuser_id) REFERENCES event_users (id)",
"ALTER TABLE lecture_participants ADD CONSTRAINT FK_lecture_participants_lecture_id FOREIGN KEY (lecture_id) REFERENCES lectures (id)"});
dbUpdates.add(new String[] { "ALTER TABLE roles ADD COLUMN select_childrens_count integer DEFAULT null;" });
}
@EJB
......
......@@ -21,13 +21,20 @@ import org.slf4j.LoggerFactory;
import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.facade.CardCodeFacade;
import fi.codecrew.moya.facade.CardObjectDataFacade;
import fi.codecrew.moya.facade.CardTemplateFacade;
import fi.codecrew.moya.facade.CardTextDataFacade;
import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.facade.GroupMembershipFacade;
import fi.codecrew.moya.facade.LanEventPropertyFacade;
import fi.codecrew.moya.facade.PrintedCardFacade;
import fi.codecrew.moya.model.CardCode;
import fi.codecrew.moya.model.CardObjectData;
import fi.codecrew.moya.model.CardTemplate;
import fi.codecrew.moya.model.CardTextData;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.GroupMembership;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.LanEventProperty;
import fi.codecrew.moya.model.LanEventPropertyKey;
......@@ -75,6 +82,17 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
@EJB
private GroupMembershipFacade gmFacade;
@EJB
private CardTextDataFacade ctdFacade;
@EJB
private CardObjectDataFacade codFacade;
@EJB
private CardCodeFacade cardCodeFacade;
// @Override
// @RolesAllowed("USER_MANAGEMENT/WRITE")
// public List<CardTemplate> findAll() {
......@@ -101,6 +119,18 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
}
@Override
@RolesAllowed(UserPermission.S_WRITE_ROLES)
public CardTextData findTextData(Integer id) {
return ctdFacade.find(id);
}
@Override
@RolesAllowed(UserPermission.S_WRITE_ROLES)
public CardObjectData findObjectData(Integer id) {
return codFacade.find(id);
}
@Override
public void checkAllUsersCardRights() {
for (EventUser u : eventUserFacade.findAll()) {
checkPrintedCard(u);
......@@ -122,24 +152,15 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
List<PrintedCard> myCards = printedcardfacade.getCards(user);
PrintedCard biggestCard = null;
// PrintedCard smallestCard = null;
for (PrintedCard card : myCards) {
// logger.info("Checking card {}", card);
if (card.getEnabled()) {
if (biggestCard == null || biggestCard.getTemplate().getPower() < card.getTemplate().getPower()) {
// The biggest card should be the only one enabled.
if (biggestCard != null) {
biggestCard.setEnabled(false);
}
biggestCard = card;
biggestCard.setEnabled(true);
}
// if (smallestCard == null ||
// smallestCard.getTemplate().getPower() >
// card.getTemplate().getPower()) {
// smallestCard = card;
// }
}
}
......@@ -179,17 +200,19 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
msg.setFromName("Lippukauppa");
msg.setToAddress(value.getTextvalue());
msg.setSubject("User " + user.getUser().getLogin() + " has too powerful card!");
msg.setMessage("User ", user.getUser().getLogin(), "has too powerful card!\nCurrent power ", existingPower, ". Should be ", newPower, "\n\n-- \nLippukauppa");
msg.setMessage("User ", user.getUser().getLogin(), "has too powerful card!\nCurrent power ", existingPower, ". Should be ", newPower, ". Card replaced with less power.\n\n-- \nLippukauppa");
mailbean.sendMail(msg);
logger.info("User {} has too much power old role {} New role {}", new Object[] { user.getUser().getLogin(), existingPower, newPower });
}
logger.info("User {} has too much power old role {} New role {}, old card revoked.", new Object[] { user.getUser().getLogin(), existingPower, newPower });
biggestCard.setEnabled(false);
return this.checkPrintedCard(user);
} else {
logger.info("User {} has power {} and roles has power {}", new Object[] { user.getUser().getLogin(), existingPower, newPower });
}
eventPropertyFacade.flush();
return biggestCard;
}
@Override
......@@ -228,6 +251,18 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
return this.printedcardfacade.findAllEnabled(eventBean.getCurrentEvent());
}
@Override
@RolesAllowed(UserPermission.S_WRITE_ROLES)
public List<CardTextData> findCardTextDatas(CardTemplate template) {
return this.ctdFacade.findAll(template);
}
@Override
@RolesAllowed(UserPermission.S_WRITE_ROLES)
public List<CardObjectData> findCardObjectDatas(CardTemplate template) {
return this.codFacade.findAll(template);
}
@RolesAllowed(UserPermission.S_WRITE_ROLES)
@Override
public CardTemplate save(CardTemplate card) {
......@@ -235,6 +270,26 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
}
@RolesAllowed(UserPermission.S_WRITE_ROLES)
@Override
public CardTextData save(CardTextData textData) {
if (textData.getId() != null && textData.getId() != 0)
textData = ctdFacade.merge(textData);
else
ctdFacade.create(textData);
return textData;
}
@RolesAllowed(UserPermission.S_WRITE_ROLES)
@Override
public CardObjectData save(CardObjectData objectData) {
if (objectData.getId() != null && objectData.getId() != 0)
objectData = codFacade.merge(objectData);
else
codFacade.create(objectData);
return objectData;
}
@Override
public PrintedCard getCard(Integer id) {
return printedcardfacade.find(id);
......@@ -305,4 +360,44 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
return card;
}
@Override
public EventUser giveCard(EventUser user, boolean markUserPlacesDelivered) {
user = eventUserFacade.reload(user);
PrintedCard card = checkPrintedCard(user);
if (card.getCardState() != CardState.DELIVERED) {
card.setCardState(CardState.DELIVERED);
} else {
logger.info("Not marking card to delivered: " + card.getCardState() + " : " + card.getId());
}
if (markUserPlacesDelivered) {
for (GroupMembership membership : gmFacade.findMemberships(user)) {
membership.setEnteredEvent(Calendar.getInstance());
}
}
return user;
}
@Override
public void removeCardCode(CardCode code) {
code = cardCodeFacade.reload(code);
if(code.getPrintedCard().getCardCodes().contains(code)) {
code.getPrintedCard().getCardCodes().remove(code);
}
cardCodeFacade.remove(code);
}
}
......@@ -150,11 +150,13 @@ public class JaasBean implements MoyaRealmBeanRemote {
}
private String restAuth(String restauth) {
String[] authsplit = restauth.split(":");
String[] authsplit = restauth.split(":", 6);
logger.info("Trying to auth with rest {}", (Object) authsplit);
if (authsplit.length != 6 || !authsplit[0].equals("rest")) {
return null;
}
return authenticateApp(authsplit[1], authsplit[2], authsplit[3], authsplit[4], authsplit[5]);
return authenticateApp(authsplit[5], authsplit[1], authsplit[2], authsplit[3], authsplit[4]);
}
@Override
......@@ -233,20 +235,33 @@ public class JaasBean implements MoyaRealmBeanRemote {
}
public String authenticateApp(String pathInfo, String appId, String userId, String appStamp, String mac) {
if (mac == null)
logger.info("Authenticat app with pathinfo {}, appid {}, userid {}, appstamp {}, mac {}",
pathInfo, appId, userId, appStamp, mac
);
if (mac == null) {
logger.warn("Rest auth failed: Mac is null");
return null;
}
ApiApplication app = appfacade.findByAppid(appId);
if (app == null)
if (app == null) {
logger.warn("Rest auth failed: Application not found for appid {}", appId);
return null;
}
ApiApplicationInstance apiInstance = appInstanceFacade.findInstance(app, userId);
if (apiInstance == null)
if (apiInstance == null) {
logger.warn("Rest auth failed; because appInstance not found for app{} and user {}", app, userId);
return null;
if (!app.isEnabled() || !apiInstance.isEnabled())
}
if (!app.isEnabled() || !apiInstance.isEnabled()) {
logger.warn("Rest auth failed: app or api-instance is disabled: app {}, apiInstance: {}", app, apiInstance);
return null;
}
String ret = null;
String macSource = PasswordFunctions.mkSeparatedString("+", pathInfo, appId, userId, appStamp, apiInstance.getSecretKey());
String macHash = PasswordFunctions.calculateSha1(macSource);
logger.info("Calculated hash {}, comparing to {}", macHash, mac);
if (mac.equalsIgnoreCase(macHash))
{
switch (app.getAuthtype()) {
......@@ -261,7 +276,10 @@ public class JaasBean implements MoyaRealmBeanRemote {
default:
throw new RuntimeException("Unknown application authtype!");
}
} else {
logger.warn("Rest auth failed: Calculated hash does not match received mac: Calculated {}, received {}", macHash, mac);
}
return ret;
}
}
package fi.codecrew.moya.beans;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import fi.codecrew.moya.enums.apps.LecturePermission;
import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.facade.LectureFacade;
import fi.codecrew.moya.facade.LectureGroupFacade;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Lecture;
import fi.codecrew.moya.model.LectureGroup;
import fi.codecrew.moya.model.Role;
/**
* Session Bean implementation class FoodWaveBean
*/
@Stateless
@DeclareRoles({ LecturePermission.S_VIEW, LecturePermission.S_MANAGE })
public class LectureBean implements LectureBeanLocal {
@EJB
LectureFacade lectureFacade;
@EJB
LectureGroupFacade lectureGroupFacade;
@EJB
EventUserFacade eventUserFacade;
@EJB
EventBean eventBean;
@EJB
UserBeanLocal userBean;
@Override
public List<Lecture> getLecturesByLectureGroup(LectureGroup group) {
return new ArrayList<Lecture>();
}
@Override
public List<LectureGroup> getLectureGroups() {
return lectureGroupFacade.getLectureGroups();
}
@Override
@RolesAllowed(LecturePermission.S_MANAGE)
public LectureGroup saveLectureGroup(LectureGroup group) {
if (group.getId() == null)
{
if (group.getEvent() == null)
group.setEvent(eventBean.getCurrentEvent());
group = lectureGroupFacade.create(group);
} else {
group = lectureGroupFacade.merge(group);
}
return group;
}
@Override
@RolesAllowed({LecturePermission.S_VIEW, LecturePermission.S_MANAGE})
public LectureGroup findLectureGroup(Integer id) {
return lectureGroupFacade.find(id);
}
@Override
@RolesAllowed(LecturePermission.S_MANAGE)
public Lecture saveLecture(Lecture lecture) {
if (lecture == null || lecture.getLectureGroup() == null) {
throw new NullPointerException("Lecture must be in some lecturegroup!");
}
// let's try this, some weird cache problem
LectureGroup group = lectureGroupFacade.reload(lecture.getLectureGroup());
lecture.setLectureGroup(group);
if (lecture.getId() == null) {
lecture = lectureFacade.create(lecture);
if (!lecture.getLectureGroup().getLectures().contains(lecture))
lecture.getLectureGroup().getLectures().add(lecture);
} else {
lecture = lectureFacade.merge(lecture);
}
return lecture;
}
@Override
@RolesAllowed({LecturePermission.S_VIEW, LecturePermission.S_MANAGE})
public List<Lecture> findAvailableLectures(LectureGroup group, EventUser user) {
LectureGroup lectureGroup = lectureGroupFacade.reload(group);
List<Role> userRoles = userBean.findUsersRoles(user);
List<Lecture> lectures = new ArrayList<Lecture>();
lectureloop: for (Lecture l : lectureGroup.getLectures()) {
for (Role r : l.getOpenForRoles()) {
if (userRoles.contains(r)) {
lectures.add(l);
continue lectureloop;
}
}
}
return lectures;
}
@Override
@RolesAllowed({LecturePermission.S_VIEW, LecturePermission.S_MANAGE})
public List<Lecture> getParticipatedLectures(EventUser user) {
return eventUserFacade.reload(user).getLectures();
}
@Override
@RolesAllowed({LecturePermission.S_VIEW, LecturePermission.S_MANAGE})
public Lecture participate(EventUser user, Lecture lecture) {
if(userLectureSelectsLeft(lecture.getLectureGroup(), user) <= 0)
return lecture;
EventUser targetUser = eventUserFacade.reload(user);
lecture.getParticipants().add(targetUser);
lectureFacade.merge(lecture);
targetUser.getLectures().add(lecture);
return lecture;
}
@Override
@RolesAllowed({LecturePermission.S_VIEW, LecturePermission.S_MANAGE})
public Lecture unparticipate(EventUser user, Lecture lecture) {
EventUser targetUser = eventUserFacade.reload(user);
lecture.getParticipants().remove(targetUser);
targetUser.getLectures().remove(lecture);
lectureFacade.merge(lecture);
return lecture;
}
@Override
@RolesAllowed({LecturePermission.S_VIEW, LecturePermission.S_MANAGE})
public int userLectureSelects(LectureGroup group, EventUser user) {
EventUser updatedUser = eventUserFacade.reload(user);
int count = 0;
for(Lecture l : updatedUser.getLectures()) {
if(l.getLectureGroup().equals(group)) {
count++;
}
}
return count;
}
@Override
@RolesAllowed({LecturePermission.S_VIEW, LecturePermission.S_MANAGE})
public int userLectureSelectsLeft(LectureGroup group, EventUser user) {
LectureGroup updatedGroup = lectureGroupFacade.reload(group);
int maxCount = updatedGroup.getSelectCount();
if(maxCount <= 0)
return 99;
return maxCount - userLectureSelects(group, user);
}
}
......@@ -15,8 +15,10 @@ import fi.codecrew.moya.enums.apps.BillPermission;
import fi.codecrew.moya.enums.apps.CompoPermission;
import fi.codecrew.moya.enums.apps.ContentPermission;
import fi.codecrew.moya.enums.apps.EventPermission;
import fi.codecrew.moya.enums.apps.LecturePermission;
import fi.codecrew.moya.enums.apps.LicensePermission;
import fi.codecrew.moya.enums.apps.MapPermission;
import fi.codecrew.moya.enums.apps.NetworkAssociationPermission;
import fi.codecrew.moya.enums.apps.PollPermission;
import fi.codecrew.moya.enums.apps.ShopPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission;
......@@ -34,6 +36,9 @@ import fi.codecrew.moya.model.MenuNavigation;
/**
*
* HUOM! JOS POISTAT SIVUN, PITÄÄ VIITTAUS POISTAA MYÖS KANNASTA! MUUTEN
* GALAKSIT RÄJÄHTÄÄ! (jsf ei löydä viittausta sivuun ja heittää poikkeuksen)
*
* Kaikki sivut pitää olla jossain menussa, muuten menu häviää näkyvistä ko.
* sivulla kokonaan. Älä siis poista sivua vaaan aseta sivu näkymättömäksi:
* .setVisible(false).
......@@ -153,7 +158,10 @@ public class MenuBean implements MenuBeanLocal {
MenuNavigation createuser = usermenu.addPage(null, null);
createuser.setKey("topnavi.createuser");
createuser.addPage(menuitemfacade.findOrCreate("/user/create"), UserPermission.CREATE_NEW).setVisible(false);
;
MenuNavigation userlectures = usermenu.addPage(null, null);
userlectures.setKey("topnavi.userlectures");
userlectures.addPage(menuitemfacade.findOrCreate("/lectures/viewLectures"), LecturePermission.VIEW);
navifacade.create(usermenu);
......@@ -167,6 +175,8 @@ public class MenuBean implements MenuBeanLocal {
MenuNavigation adminuser = adminmenu.addPage(null, null);
adminuser.setKey("topnavi.usermgmt");
adminuser.addPage(menuitemfacade.findOrCreate("/useradmin/list"), UserPermission.VIEW_ALL);
adminuser.addPage(menuitemfacade.findOrCreate("/useradmin/overview"), UserPermission.VIEW_ALL).setVisible(false);
adminuser.addPage(menuitemfacade.findOrCreate("/useradmin/create"), UserPermission.VIEW_ALL);
adminuser.addPage(menuitemfacade.findOrCreate("/useradmin/sendPicture"), UserPermission.VIEW_ALL).setVisible(false);
adminuser.addPage(menuitemfacade.findOrCreate("/place/adminGroups"), UserPermission.VIEW_ALL).setVisible(false);
......@@ -191,10 +201,16 @@ public class MenuBean implements MenuBeanLocal {
adminEventCards.setKey("subnavi.cards");
adminEventCards.addPage(menuitemfacade.findOrCreate("/useradmin/listCardTemplates"), UserPermission.READ_ROLES);
adminEventCards.addPage(menuitemfacade.findOrCreate("/useradmin/createCardTemplate"), UserPermission.WRITE_ROLES);
adminEventCards.addPage(menuitemfacade.findOrCreate("/useradmin/editCardTextData"), UserPermission.WRITE_ROLES).setVisible(false);
adminEventCards.addPage(menuitemfacade.findOrCreate("/useradmin/listCardTemplateData"), UserPermission.READ_ROLES).setVisible(false);
adminEventCards.addPage(menuitemfacade.findOrCreate("/useradmin/editCardTemplate"), null).setVisible(false);
adminEventCards.addPage(menuitemfacade.findOrCreate("/shop/shopToUser"), null).setVisible(false);
adminEventCards.addPage(menuitemfacade.findOrCreate("/shop/assocToUser"), null).setVisible(false);
MenuNavigation adminAssociation = adminmenu.addPage(null, null);
adminAssociation.setKey("topnavi.adminassoc");
adminAssociation.addPage(menuitemfacade.findOrCreate("/networkassociation/index"), NetworkAssociationPermission.CAN_ADMINISTER_ASSOCIATIONS);
// shop
MenuNavigation adminshop = adminmenu.addPage(null, null);
adminshop.setKey("topnavi.adminshop");
......@@ -276,14 +292,23 @@ public class MenuBean implements MenuBeanLocal {
tournamentsadm.addPage(menuitemfacade.findOrCreate("/tournaments/admin/delete"), TournamentPermission.MANAGE_ALL).setVisible(false);
tournamentsadm.addPage(menuitemfacade.findOrCreate("/tournaments/admin/editrules"), TournamentPermission.MANAGE_ALL).setVisible(false);
MenuNavigation adminlectures = adminmenu.addPage(null, null);
adminlectures.setKey("topnavi.adminlectures");
adminlectures.addPage(menuitemfacade.findOrCreate("/lectureadmin/manageLectureGroups"), LecturePermission.MANAGE);
MenuNavigation infoviews = adminmenu.addPage(null, null);
infoviews.setKey("topnavi.infoviews");
infoviews.addPage(menuitemfacade.findOrCreate("/admin/adduser/index"), TerminalPermission.INFO);
MenuNavigation infonavi = infoviews.addPage(null, null);
infonavi.setKey("subnavi.info");
infonavi.addPage(menuitemfacade.findOrCreate("/info/index"), TerminalPermission.INFO);
infonavi.addPage(menuitemfacade.findOrCreate("/info/incoming"), TerminalPermission.INFO);
infonavi.addPage(menuitemfacade.findOrCreate("/info/shop"), TerminalPermission.INFO);
navifacade.create(adminmenu);
......
......@@ -9,6 +9,8 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
......@@ -622,7 +624,12 @@ public class PlaceBean implements PlaceBeanLocal {
@Override
public byte[] generatePlacesPdf(float width, float height, double font1, double font2) {
try {
return generatePlacesPdf(width, height, font1, font1, placeFacade.findAll());
List<Place> places = placeFacade.findAll();
Collections.sort(places);
logger.info("sorting places etc.");
return generatePlacesPdf(width, height, font1, font1, places);
} catch (Exception e) {
logger.error("Exception from place pdf generation.", e);
......
......@@ -267,7 +267,13 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
@Override
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public void releaseAndGenerateToken(GroupMembership gmem) {
if(gmem.getEnteredEvent() != null && !permbean.hasPermission(MapPermission.MANAGE_OTHERS)) {
throw new EJBAccessException("Token already entered to event, Not enough rights to release token.");
}
gmem = gmemfacade.reload(gmem);
if (!(permbean.getCurrentUser().getId().equals(gmem.getPlaceGroup().getCreator().getId()) || permbean.hasPermission(MapPermission.MANAGE_OTHERS))) {
loggerbean.logMessage(SecurityLogType.permissionDenied, permbean.getCurrentUser(), "User tried to release and generate group membership: " + gmem);
throw new EJBAccessException("Not enough rights to release token");
......
......@@ -79,50 +79,4 @@ public class PlaceMapBean implements PlaceMapBeanLocal {
return null;
}
/*
wanha, poistoon
public byte[] placeCodesPdf(List<Place> places) {
// double[] pageSize = new double[] { cardBackground.getWidth(),
// cardBackground.getHeight() };
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PDF pdf;
try {
pdf = new PDF(outputStream);
pdf.setTitle("placecodes");
double pagex = 155.9;
double pagey = 48;
Page page = new Page(pdf, new double[] { pagex, pagey });
// Render texts
// Big font for nick
com.pdfjet.Font font = new com.pdfjet.Font(pdf, CoreFont.HELVETICA);
font.setSize(8.0);
TextLine line = new TextLine(font);
line.setText("testi");
line.setPosition(1, 1);
line.setColor(new double[] { 1.0, 1.0, 1.0 });
line.drawOn(page);
pdf.flush();
outputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return outputStream.toByteArray();
}
*/
}
......@@ -164,7 +164,7 @@ public class ReaderBean implements ReaderBeanLocal {
}
}
event = readerEventFacade.create(event);
readerEventFacade.create(event);
return event;
......@@ -175,8 +175,7 @@ public class ReaderBean implements ReaderBeanLocal {
CardCode code = new CardCode(card, readerEvent.getReader().getType(), readerEvent.getValue());
code = cardCodeFacade.create(code);
card = cardfacade.reload(card);
cardCodeFacade.create(code);
return readerEvent;
}
......
......@@ -70,13 +70,15 @@ public class TournamentBean implements TournamentBeanLocal {
@Override
@RolesAllowed(TournamentPermission.S_MANAGE_ALL)
public TournamentGame createGame(TournamentGame tg) {
return tournamentGameFacade.create(tg);
tournamentGameFacade.create(tg);
return tg;
}
@Override
@RolesAllowed(TournamentPermission.S_MANAGE_ALL)
public TournamentRule createRule(TournamentRule tr) {
return tournamentRuleFacade.create(tr);
tournamentRuleFacade.create(tr);
return tr;
}
@Override
......@@ -100,12 +102,12 @@ public class TournamentBean implements TournamentBeanLocal {
else
throw new Exception("tournament.invalid_event");
}
@Override
@RolesAllowed(TournamentPermission.S_MANAGE_ALL)
public void updateTournamentRules(TournamentRule tr) throws Exception {
// Assert correct event
if(eventBean.getCurrentEvent().equals(tr.getTournamentGame().getLanEvent())) {
if (eventBean.getCurrentEvent().equals(tr.getTournamentGame().getLanEvent())) {
tournamentRuleFacade.merge(tr);
} else {
throw new Exception("tournament.invalid_event");
......@@ -115,8 +117,8 @@ public class TournamentBean implements TournamentBeanLocal {
@Override
@RolesAllowed(TournamentPermission.S_VIEW)
public List<Tournament> getTournamentsInStatus(TournamentStatus status, boolean useTimeConstraints, boolean invertMatch) {
if(useTimeConstraints)
if(!invertMatch)
if (useTimeConstraints)
if (!invertMatch)
return tournamentFacade.getTournamentsInStatusWithParticipationTimeIn(status, eventBean.getCurrentEvent());
else
return tournamentFacade.getTournamentsInStatusWithParticipationTimeNotIn(status, eventBean.getCurrentEvent());
......@@ -170,7 +172,7 @@ public class TournamentBean implements TournamentBeanLocal {
// Assert team has the correct number of players for a match
if (tournamentParticipant.getTeamMembers().size() >= tournamentParticipant.getTournament().getPlayersPerMatch()) {
tournamentParticipant = tournamentParticipantFacade.create(tournamentParticipant);
tournamentParticipantFacade.create(tournamentParticipant);
t.getParticipants().add(tournamentParticipant);
} else {
throw new Exception("tournament.not_enough_players");
......@@ -206,10 +208,10 @@ public class TournamentBean implements TournamentBeanLocal {
@RolesAllowed(TournamentPermission.S_VIEW)
public List<TournamentParticipant> findOwnParticipations() {
EventUser currentUser = permissionBean.getCurrentUser();
return tournamentParticipantFacade.findByParticipator(currentUser);
}
@Override
@RolesAllowed(TournamentPermission.S_VIEW)
public EventUser findAvailablePlayerForTournamentByLogin(Tournament t, String login) throws Exception {
......@@ -230,27 +232,27 @@ public class TournamentBean implements TournamentBeanLocal {
public void deleteParticipationById(Integer tpid) throws Exception {
TournamentParticipant tp = tournamentParticipantFacade.find(tpid);
EventUser executor = permissionBean.getCurrentUser();
// Assert we have permission to remove participant
// TODO: this will include check for remove any participation too!
if(!permissionBean.hasPermission(TournamentPermission.REMOVE_OWN_PARTICIPATION) || !tp.getParticipator().equals(executor)) {
if (!permissionBean.hasPermission(TournamentPermission.REMOVE_OWN_PARTICIPATION) || !tp.getParticipator().equals(executor)) {
throw new Exception("tournaments.can_only_remove_own_participations");
}
// Assert that tournament has not closed participation
// TODO: admin exception!
if(!tp.getTournament().getRegistrationClosesAt().after(new Date())) {
if (!tp.getTournament().getRegistrationClosesAt().after(new Date())) {
throw new Exception("tournaments.cannot_remove_participation_from_closed_tournament");
}
// All ok, do nukage
for(TournamentTeamMember ttm : tp.getTeamMembers()) {
for (TournamentTeamMember ttm : tp.getTeamMembers()) {
tournamentTeamMemberFacade.remove(ttm);
}
// Let's not leave anything in cache :)
tp.getTournament().getParticipants().remove(tp);
tournamentParticipantFacade.remove(tp);
}
}
......@@ -8,6 +8,8 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
......@@ -28,9 +30,11 @@ import javax.imageio.ImageIO;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.enums.apps.EventPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.enums.apps.UserPermission;
......@@ -42,6 +46,7 @@ import fi.codecrew.moya.facade.FeedbackFacade;
import fi.codecrew.moya.facade.GameIDFacade;
import fi.codecrew.moya.facade.GroupMembershipFacade;
import fi.codecrew.moya.facade.PlaceGroupFacade;
import fi.codecrew.moya.facade.PrintedCardFacade;
import fi.codecrew.moya.facade.ProductFacade;
import fi.codecrew.moya.facade.RoleFacade;
import fi.codecrew.moya.facade.UserApprovalFacade;
......@@ -121,6 +126,10 @@ public class UserBean implements UserBeanLocal {
@EJB
private UserImageFacade imagefacade;
// changed bean to this bcause of loop
@EJB
private PrintedCardFacade printedcardfacade;
@EJB
private LoggingBeanLocal loggerbean;
......@@ -147,6 +156,7 @@ public class UserBean implements UserBeanLocal {
@EJB
private ProductFacade productFacade;
@Override
@RolesAllowed(UserPermission.S_VIEW_ALL)
public List<EventUser> getUsers() {
......@@ -321,38 +331,41 @@ public class UserBean implements UserBeanLocal {
}
private BufferedImage forceCrop(BufferedImage source) {
int x, y, xl, yl, xh, yh, xc, yc, x0, y0, x1, y1;
double ar = CardPrintBean.ASPECT_RATIO; // x/y
x = source.getWidth();
y = source.getHeight();
xc = x / 2;
yc = y / 2;
if (y >= x) {
xl = x;
yl = (int) (y * ((double) x / (double) y));
int targetWidth, targetHeight;
double targetRatio = CardPrintBean.ASPECT_RATIO; // x/y
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();
int sourceCenterX = sourceWidth / 2;
int sourceCenterY = sourceHeight / 2;
int sourceTop, sourceLeft, sourceRight, sourceBottom;
double sourceRatio = (double) sourceWidth / (double) sourceHeight;
if (sourceRatio > targetRatio) {
// the pic is too wide - reduce width
targetWidth = (int) ((double) sourceHeight * targetRatio);
targetHeight = sourceHeight;
// crop box coords - calculate left and right
sourceLeft = sourceCenterX - (targetWidth / 2);
sourceTop = 0;
sourceRight = sourceCenterX + (targetWidth / 2);
sourceBottom = sourceHeight;
} else {
xl = (int) (x * ((double) y / (double) x));
yl = y;
// the pic is too tall - reduce height
targetWidth = sourceWidth;
targetHeight = (int) ((double) sourceWidth / targetRatio);
// crop box coords - calculate top and bottom
sourceLeft = 0;
sourceTop = sourceCenterY - (targetHeight / 2);
sourceRight = sourceWidth;
sourceBottom = sourceCenterY + (targetHeight / 2);
}
xh = (int) ((xl / 2) * ar);
yh = yl / 2;
x0 = xc - xh;
x1 = xc + xh;
y0 = yc - yh;
y1 = yc + yh;
int cix = (int) (((double) xl) * ar);
int ciy = yl;
BufferedImage cropped = new BufferedImage(cix, ciy, source.getType());
BufferedImage cropped = new BufferedImage(targetWidth, targetHeight, source.getType());
Graphics2D g = cropped.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(source, 0, 0, cix, ciy, x0, y0, x1, y1, null);
g.drawImage(source, 0, 0, targetWidth, targetHeight, sourceLeft, sourceTop, sourceRight, sourceBottom, null);
g.dispose();
return cropped;
......@@ -463,6 +476,38 @@ public class UserBean implements UserBeanLocal {
return true;
}
public PrintedCard rejectPrintedCard(PrintedCard card, MailMessage mail) {
if (card != null) {
card.setCardState(CardState.REJECTED);
card = printedcardfacade.merge(card);
logger.info("rejectPrintedCard(): Rejected card {}, state {}", card, card.getCardState());
User user = null;
if (card.getUser() != null && card.getUser().getUser() != null)
user = card.getUser().getUser();
LanEvent event = card.getEvent();
if (mail != null) {
if (!utilbean.sendMail(mail)) {
logger.info("Sending mail failed");
} else
logger.info("Sending mail succeeded");
} else {
if (user == null)
logger.info("user is null");
if (event == null)
logger.info("event is null");
}
}
logger.info("returning card");
return card;
}
// @Override
// @RolesAllowed(UserPermission.S_VIEW_ALL)
// public User findById(Integer id) {
......@@ -618,7 +663,7 @@ public class UserBean implements UserBeanLocal {
gid.setGame(game);
gid.setUser(u);
gid = gameIDFacade.create(gid);
gameIDFacade.create(gid);
u.getGameIDs().add(gid);
}
......@@ -898,4 +943,94 @@ public class UserBean implements UserBeanLocal {
}
@Override
@RolesAllowed(EventPermission.S_MANAGE_EVENT)
public String getAuthCode(EventUser user) {
logger.info("getAuthCode()");
String code = "";
String hex = Integer.toHexString(user.getId());
logger.info("Hex code {} for id {}", hex, user.getId());
// padding hex string to 5 characters by adding Xs to the beginning
if (hex.length() < 5) {
logger.info("Padding hex ({}) with X.", hex.length());
for (int i = 0; i < 5; i++) {
if (hex.length() < 5) {
hex = "X" + hex;
}
else
break;
}
} else
logger.info("Hex string too long ({}), no padding needed", hex.length());
String hash = "";
logger.info("Generating md5 hash from hex {}", hex);
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(hex.getBytes());
hash = new String(Hex.encodeHex(array));
logger.info("Hash {}", hash);
} catch (NoSuchAlgorithmException ex) {
logger.info("Catched exeption {}", ex.getMessage());
}
if (hash != "" && hash.length() > 2) {
// Generating code by concatenating hex string and first 3
// characters from hash
code = code.concat(hex);
code = code.concat(hash.substring(0, 3));
logger.info("Code for user is {}", code);
} else
logger.info("No code generated: hash.length() {}", hash.length());
return code.toUpperCase();
}
@Override
@RolesAllowed(EventPermission.S_MANAGE_EVENT)
public EventUser getUser(String authcode) {
logger.info("getUser({})", authcode);
EventUser user = null;
if (authcode.length() == 8) {
logger.info("authcode length is 8");
// First 5 characters are the hex
String paddedHex = authcode.substring(0, 5);
logger.info("Padded hex {}", paddedHex);
// Removing the padding characters
String hex = paddedHex.replace("X", "");
logger.info("Hex {}", hex);
int id = 0;
try {
id = Integer.decode("0x" + hex.toLowerCase());
} catch (NumberFormatException ex) {
logger.info("NumberFormatException was thrown");
}
logger.info("Id {}", id);
if (id != 0) {
user = eventUserFacade.find(id);
}
if (user != null) {
// Testing if the user is correct
logger.info("User {} found with id {}", user, id);
String testCode = getAuthCode(user);
logger.info("Testcode {}", testCode);
if (testCode == null || testCode.equals("") || !authcode.equals(testCode)) {
user = null;
logger.info("User set to null, test code not the same as user that was found.");
}
} else
logger.info("User not found with id {}", id);
} else
logger.info("authcode length not 8!, length {}", authcode.length());
return user;
}
}
\ No newline at end of file
package fi.codecrew.moya.facade;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.CardObjectData;
import fi.codecrew.moya.model.CardObjectData_;
import fi.codecrew.moya.model.CardTemplate_;
import fi.codecrew.moya.model.CardTextData;
import fi.codecrew.moya.model.CardTextData_;
import fi.codecrew.moya.beans.CardTemplateBeanLocal;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.CardTemplate;
@Stateless
@LocalBean
public class CardObjectDataFacade extends IntegerPkGenericFacade<CardObjectData> {
@EJB
private EventBeanLocal eventbean;
@EJB
private CardTemplateBeanLocal ctbean;
public CardObjectDataFacade() {
super(CardObjectData.class);
}
public List<CardObjectData> findAll(CardTemplate template)
{
//CardTemplate template = ctbean.find(templateId);
if(template != null) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<CardObjectData> cq = cb.createQuery(CardObjectData.class);
Root<CardObjectData> root = cq.from(CardObjectData.class);
cq.where(cb.equal(root.get(CardObjectData_.cardTemplate), template));
return getEm().createQuery(cq).getResultList();
} else
return null;
}
}
package fi.codecrew.moya.facade;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.CardTemplate_;
import fi.codecrew.moya.model.CardTextData;
import fi.codecrew.moya.model.CardTextData_;
import fi.codecrew.moya.beans.CardTemplateBeanLocal;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.CardTemplate;
@Stateless
@LocalBean
public class CardTextDataFacade extends IntegerPkGenericFacade<CardTextData> {
@EJB
private EventBeanLocal eventbean;
@EJB
private CardTemplateBeanLocal ctbean;
public CardTextDataFacade() {
super(CardTextData.class);
}
public List<CardTextData> findAll(CardTemplate template)
{
//CardTemplate template = ctbean.find(templateId);
if(template != null) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<CardTextData> cq = cb.createQuery(CardTextData.class);
Root<CardTextData> root = cq.from(CardTextData.class);
cq.where(cb.equal(root.get(CardTextData_.cardTemplate), template));
return getEm().createQuery(cq).getResultList();
} else
return null;
}
}
package fi.codecrew.moya.facade;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Lecture;
@Stateless
@LocalBean
public class LectureFacade extends IntegerPkGenericFacade<Lecture> {
public LectureFacade() {
super(Lecture.class);
}
}
package fi.codecrew.moya.facade;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.LectureGroup;
import fi.codecrew.moya.model.LectureGroup_;
@Stateless
@LocalBean
public class LectureGroupFacade extends IntegerPkGenericFacade<LectureGroup> {
public LectureGroupFacade() {
super(LectureGroup.class);
}
@EJB
EventBeanLocal eventBean;
public List<LectureGroup> getLectureGroups() {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<LectureGroup> cq = cb.createQuery(LectureGroup.class);
Root<LectureGroup> root = cq.from(LectureGroup.class);
cq.where(cb.equal(root.get(LectureGroup_.event), eventBean.getCurrentEvent() ) );
return getEm().createQuery(cq).getResultList();
}
}
package fi.codecrew.moya.facade;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.enums.NetworkAssociationStatus;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.NetworkAssociation;
import fi.codecrew.moya.model.NetworkAssociation_;
import fi.codecrew.moya.model.Place;
@Stateless
@LocalBean
public class NetworkAssociationFacade extends IntegerPkGenericFacade<NetworkAssociation> {
public NetworkAssociationFacade() { super(NetworkAssociation.class); }
public List<NetworkAssociation> findByIPAndMACAndStatus(LanEvent event, String ip, String mac, NetworkAssociationStatus nas) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<NetworkAssociation> cq = cb.createQuery(NetworkAssociation.class);
Root<NetworkAssociation> root = cq.from(NetworkAssociation.class);
cq.where(
cb.and(
cb.equal(root.get(NetworkAssociation_.event), event),
cb.equal(root.get(NetworkAssociation_.ip), ip),
cb.equal(root.get(NetworkAssociation_.mac), mac),
cb.equal(root.get(NetworkAssociation_.status), nas)
)
);
return getEm().createQuery(cq).getResultList();
}
public List<NetworkAssociation> findActiveAssociationsByIP(LanEvent event, String ip) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<NetworkAssociation> cq = cb.createQuery(NetworkAssociation.class);
Root<NetworkAssociation> root = cq.from(NetworkAssociation.class);
cq.where(
cb.and(
cb.equal(root.get(NetworkAssociation_.event), event),
cb.or(
cb.equal(root.get(NetworkAssociation_.status), NetworkAssociationStatus.PENDING),
cb.equal(root.get(NetworkAssociation_.status), NetworkAssociationStatus.ACTIVE)
),
cb.equal(root.get(NetworkAssociation_.ip), ip)
)
);
return getEm().createQuery(cq).getResultList();
}
public List<NetworkAssociation> findActiveAssociationsByPlace(Place place) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<NetworkAssociation> cq = cb.createQuery(NetworkAssociation.class);
Root<NetworkAssociation> root = cq.from(NetworkAssociation.class);
cq.where(
cb.and(
cb.or(
cb.equal(root.get(NetworkAssociation_.status), NetworkAssociationStatus.PENDING),
cb.equal(root.get(NetworkAssociation_.status), NetworkAssociationStatus.ACTIVE)
),
cb.equal(root.get(NetworkAssociation_.place), place)
)
);
return getEm().createQuery(cq).getResultList();
}
public List<NetworkAssociation> findByIPAndMAC(LanEvent event, String ip, String mac) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<NetworkAssociation> cq = cb.createQuery(NetworkAssociation.class);
Root<NetworkAssociation> root = cq.from(NetworkAssociation.class);
cq.where(
cb.and(
cb.equal(root.get(NetworkAssociation_.event), event),
cb.equal(root.get(NetworkAssociation_.ip), ip),
cb.equal(root.get(NetworkAssociation_.mac), mac)
)
);
return getEm().createQuery(cq).getResultList();
}
public List<NetworkAssociation> findByStatus(LanEvent event, NetworkAssociationStatus status) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<NetworkAssociation> cq = cb.createQuery(NetworkAssociation.class);
Root<NetworkAssociation> root = cq.from(NetworkAssociation.class);
cq.where(
cb.and(
cb.equal(root.get(NetworkAssociation_.event), event),
cb.equal(root.get(NetworkAssociation_.status), status)
)
);
return getEm().createQuery(cq).getResultList();
}
public List<NetworkAssociation> findByStatusAndHorizon(LanEvent event, NetworkAssociationStatus status, String horizon) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<NetworkAssociation> cq = cb.createQuery(NetworkAssociation.class);
Root<NetworkAssociation> root = cq.from(NetworkAssociation.class);
cq.where(
cb.and(
cb.equal(root.get(NetworkAssociation_.event), event),
cb.equal(root.get(NetworkAssociation_.status), status),
cb.like(root.get(NetworkAssociation_.ip), horizon+"%")
)
);
return getEm().createQuery(cq).getResultList();
}
}
......@@ -89,12 +89,6 @@ public class UserFacade extends IntegerPkGenericFacade<User> {
// }
@Override
public User create(User user) {
user.setLogin(user.getLogin().toLowerCase().trim());
return super.create(user);
}
@Override
public User merge(User user) {
user.setLogin(user.getLogin().toLowerCase().trim());
return super.merge(user);
......
......@@ -6,10 +6,12 @@ import java.util.List;
import javax.ejb.Local;
import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.model.CardCode;
import fi.codecrew.moya.model.CardObjectData;
import fi.codecrew.moya.model.CardTemplate;
import fi.codecrew.moya.model.CardTextData;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.PrintedCard;
import fi.codecrew.moya.model.ReaderEvent;
import fi.codecrew.moya.utilities.jsf.EntityFinderBean;
@Local
......@@ -24,8 +26,16 @@ public interface CardTemplateBeanLocal extends EntityFinderBean<CardTemplate> {
void checkAllUsersCardRights();
List<PrintedCard> findActiveCards();
List<CardTextData> findCardTextDatas(CardTemplate template);
List<CardObjectData> findCardObjectDatas(CardTemplate template);
CardTemplate save(CardTemplate card);
CardTextData save(CardTextData textData);
CardObjectData save(CardObjectData objectData);
PrintedCard getCard(Integer idParam);
......@@ -43,8 +53,15 @@ public interface CardTemplateBeanLocal extends EntityFinderBean<CardTemplate> {
PrintedCard findCard(Integer id);
CardTextData findTextData(Integer id);
CardObjectData findObjectData(Integer id);
List<PrintedCard> getCardsByState(CardState... pendingPrint);
PrintedCard setCardState(Integer cardId, CardState printed) throws Exception;
EventUser giveCard(EventUser user, boolean markUserPlacesDelivered);
void removeCardCode(CardCode code);
}
package fi.codecrew.moya.beans;
import java.util.List;
import javax.ejb.Local;
import javax.faces.model.ListDataModel;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Lecture;
import fi.codecrew.moya.model.LectureGroup;
@Local
public interface LectureBeanLocal {
public List<Lecture> getLecturesByLectureGroup(LectureGroup group);
public List<LectureGroup> getLectureGroups();
public LectureGroup saveLectureGroup(LectureGroup group);
public LectureGroup findLectureGroup(Integer id);
public Lecture saveLecture(Lecture lecture);
public List<Lecture> findAvailableLectures(LectureGroup group, EventUser user);
public List<Lecture> getParticipatedLectures(EventUser user);
public Lecture participate(EventUser user, Lecture lecture);
public Lecture unparticipate(EventUser user, Lecture lecture);
public int userLectureSelectsLeft(LectureGroup group, EventUser user);
public int userLectureSelects(LectureGroup group, EventUser user);
}
package fi.codecrew.moya.beans;
import java.util.List;
import javax.ejb.Local;
import fi.codecrew.moya.model.NetworkAssociation;
@Local
public interface NetworkAssociationBeanLocal {
NetworkAssociation tryAssociate(String username, String password,
String ip, String mac, String code, boolean codeRequired)
throws Exception;
List<NetworkAssociation> getStatusByIPAndMAC(String ip, String mac);
List<NetworkAssociation> getActiveAssociations(boolean activatePending);
NetworkAssociation tryAssociate(String ip, String mac);
List<NetworkAssociation> getPendingAssociations();
void dropAssociationById(Integer associd);
NetworkAssociation getActiveAssociationByIP(String ipAddress);
NetworkAssociation tryAssociate(String usercode, String ip, String mac,
String code, Boolean codeRequired) throws Exception;
List<NetworkAssociation> getActiveAssociationsByHorizon(Boolean activate,
String horizon);
}
......@@ -12,11 +12,13 @@ import fi.codecrew.moya.model.Feedback;
import fi.codecrew.moya.model.GameID;
import fi.codecrew.moya.model.GroupMembership;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.PrintedCard;
import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.model.TournamentGame;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.UserApproval;
import fi.codecrew.moya.model.UserImage;
import fi.codecrew.moya.util.MailMessage;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchQuery;
import fi.codecrew.moya.utilities.SearchResult;
......@@ -98,6 +100,8 @@ public interface UserBeanLocal {
boolean initPasswordResetForEmail(String email, String url);
PrintedCard rejectPrintedCard(PrintedCard card, MailMessage mail);
boolean initPasswordResetForUsername(String username, String url);
void addGameID(TournamentGame game, String gameid);
......@@ -127,4 +131,7 @@ public interface UserBeanLocal {
*/
BigDecimal transferAccountSaldoFromPreviousEvent(List<User> dstEventuser, LanEvent source);
EventUser getUser(String authcode);
String getAuthCode(EventUser user);
}
eclipse.preferences.version=1
entitygen.DEFAULT_PACKAGE=model
org.eclipse.jpt.core.discoverAnnotatedClasses=true
org.eclipse.jpt.core.platform=eclipselink2_5
org.eclipse.jpt.jpa.core.discoverAnnotatedClasses=true
......
......@@ -60,7 +60,18 @@
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1100-jdbc41</version>
<version>9.3-1101-jdbc41</version>
</dependency>
<dependency>
<groupId>org.ancoron.postgresql</groupId>
<artifactId>org.postgresql.net</artifactId>
<version>9.1.901.jdbc4.1-rc9</version>
<exclusions>
<exclusion>
<artifactId>org.postgresql</artifactId>
<groupId>org.ancoron.postgresql</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
\ No newline at end of file
......@@ -12,14 +12,13 @@
<property name="eclipselink.logging.logger" value="ServerLogger" />
<property name="eclipselink.jdbc.uppercase-columns" value="false" />
<property name="eclipselink.target-database"
value="fi.codecrew.moya.database.MoyaPostgreSQLPlatform" />
<property name="eclipselink.session-event-listener"
value="org.ancoron.postgresql.jpa.eclipselink.ConverterInitializer" />
<property name="eclipselink.descriptor.customizer"
value="fi.codecrew.moya.database.MoyaDescriptorCustomizer" />
<property name="eclipselink.create-ddl-jdbc-file-name" value="moyaCreateDDL.sql"/>
<property name="eclipselink.drop-ddl-jdbc-file-name" value="moyaDropDDL.sql"/>
value="fi.codecrew.moya.database.eclipselink.MoyaPostgreSQLPlatform" />
<property name="eclipselink.create-ddl-jdbc-file-name" value="moyaCreateDDL.sql" />
<property name="eclipselink.drop-ddl-jdbc-file-name" value="moyaDropDDL.sql" />
<property name="eclipselink.target-server" value="Glassfish" />
<property name="eclipselink.session.customizer"
value="fi.codecrew.moya.database.eclipselink.MoyaSessionCustomizer" />
</properties>
</persistence-unit>
</persistence>
package fi.codecrew.moya.database.eclipselink;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.persistence.descriptors.ChangedFieldsLockingPolicy;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.internal.helper.DatabaseTable;
import org.eclipse.persistence.internal.sessions.AbstractRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Filters out JSON fields from Optimistic Locking policy that checks changed
* fields. JSON fields in PostgreSQL cannot be compared.
*
* @author jkj
*
*/
public class MoyaChangedFieldsOptimisticLockingPolicy extends ChangedFieldsLockingPolicy {
private static final long serialVersionUID = -1951931955910848024L;
private static final Logger log = LoggerFactory.getLogger(MoyaChangedFieldsOptimisticLockingPolicy.class);
/**
* Skip PGobject from ChangedFieldsLockingPolicy. PostgreSQL does not now
* how to compare JSON column, and this was the easiest way to work around
* it.
*/
@Override
protected List<DatabaseField> getFieldsToCompare(DatabaseTable table, AbstractRecord transRow, AbstractRecord modifyRow) {
// log.info("getFieldsToCompare({}, {}, {})", table, transRow,
// modifyRow);
List<DatabaseField> changedFields = super.getFieldsToCompare(table, transRow, modifyRow);
ArrayList<DatabaseField> fieldsToCompare = new ArrayList<DatabaseField>(changedFields.size());
// Filter out JSON fields because they cannot be compared
for (DatabaseField f : changedFields) {
// log.info("Field with typeName={}: {}", f.toString(),
// f.getTypeName());
if (!f.getTypeName().equals("org.postgresql.util.PGobject")) {
log.debug("Ignoring a PGobject field from changed fields optimistic locking policy: {}", f);
fieldsToCompare.add(f);
}
}
return fieldsToCompare;
}
}
package fi.codecrew.moya.database;
package fi.codecrew.moya.database.eclipselink;
import java.util.List;
import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ChangedFieldsLockingPolicy;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.descriptors.ReturningPolicy;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MoyaDescriptorCustomizer implements DescriptorCustomizer {
@Override
public void customize(ClassDescriptor descriptor) throws Exception {
// Optimistic locking policy
ChangedFieldsLockingPolicy changedFieldsLockingPolicy = new ChangedFieldsLockingPolicy();
descriptor.setOptimisticLockingPolicy(changedFieldsLockingPolicy);
// Returningpolicy
ReturningPolicy returningPolicy = new ReturningPolicy();
List<DatabaseField> pkFields = descriptor.getPrimaryKeyFields();
for (final DatabaseField field : pkFields) {
returningPolicy.addFieldForInsertReturnOnly(field);
field.setUpdatable(false);
field.setInsertable(false);
}
for (final DatabaseField field : descriptor.getFields()) {
if (pkFields.contains(field))
continue;
returningPolicy.addFieldForInsert(field);
returningPolicy.addFieldForUpdate(field);
}
descriptor.setReturningPolicy(returningPolicy);
}
private static final Logger log = LoggerFactory.getLogger(MoyaDescriptorCustomizer.class);
@Override
public void customize(ClassDescriptor descriptor) throws Exception {
log.info("Customizing Descriptor: {}", descriptor);
// Optimistic locking policy
MoyaChangedFieldsOptimisticLockingPolicy changedFieldsLockingPolicy = new MoyaChangedFieldsOptimisticLockingPolicy();
// log.debug("Setting Optimistic Locking Policy: {}",
// changedFieldsLockingPolicy);
descriptor.setOptimisticLockingPolicy(changedFieldsLockingPolicy);
// ReturningPolicy
ReturningPolicy returningPolicy = new ReturningPolicy();
descriptor.setReturningPolicy(returningPolicy);
/*
* // generation strategy IDENTITY has sequence number field
* DatabaseField seqNumberField = descriptor.getSequenceNumberField();
* if (seqNumberField != null) {
* returningPolicy.addFieldForInsertReturnOnly(seqNumberField); }
*/
List<DatabaseField> pkFields = descriptor.getPrimaryKeyFields();
for (final DatabaseField field : pkFields) {
returningPolicy.addFieldForInsertReturnOnly(field);
field.setUpdatable(false);
field.setInsertable(false);
}
/*
* for (final DatabaseField field : descriptor.getFields()) {
*
* if (pkFields.contains(field)) continue;
*
* returningPolicy.addFieldForInsert(field);
* returningPolicy.addFieldForUpdate(field); }
*/
// log.info("Set descriptor's RETURNING policy to: {}",
// returningPolicy);
}
}
package fi.codecrew.moya.database;
package fi.codecrew.moya.database.eclipselink;
import java.util.Hashtable;
import org.ancoron.postgresql.jpa.eclipselink.ExtendedPostgreSQLPlatform;
import org.eclipse.persistence.internal.databaseaccess.FieldTypeDefinition;
import org.eclipse.persistence.platform.database.PostgreSQLPlatform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MoyaPostgreSQLPlatform extends PostgreSQLPlatform {
private static final long serialVersionUID = 6351395815598077327L;
/**
* Smarter defaults. Use TEXT for string columns and understand JSON fields.
* Also inherit ExtendedPostgreSQLPlatform which understand the Inet types.
*
* @author jkj
*
*/
public class MoyaPostgreSQLPlatform extends ExtendedPostgreSQLPlatform {
private static final long serialVersionUID = 6351395815598077327L;
private static final Logger log = LoggerFactory.getLogger(MoyaPostgreSQLPlatform.class);
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected Hashtable buildFieldTypes() {
Hashtable map = super.buildFieldTypes();
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected Hashtable buildFieldTypes() {
log.info("Customizing SQL Platform field types for Moya");
Hashtable map = super.buildFieldTypes();
map.put(String.class, new FieldTypeDefinition("TEXT", false));
map.put(java.sql.Timestamp.class, new FieldTypeDefinition("TIMESTAMPTZ", false));
map.put(javax.json.JsonObject.class, new FieldTypeDefinition("JSON", false));
map.put(String.class, new FieldTypeDefinition("TEXT", false));
map.put(java.sql.Timestamp.class, new FieldTypeDefinition("TIMESTAMPTZ", false));
map.put(javax.json.JsonObject.class, new FieldTypeDefinition("JSON", false));
return map;
}
return map;
}
}
package fi.codecrew.moya.database.eclipselink;
import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.sessions.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MoyaSessionCustomizer implements SessionCustomizer {
private static final Logger log = LoggerFactory.getLogger(MoyaSessionCustomizer.class);
@Override
public void customize(Session session) throws Exception {
log.info("Customizing session: {}", session);
MoyaDescriptorCustomizer customizer = new MoyaDescriptorCustomizer();
for (ClassDescriptor descriptor : session.getDescriptors().values()) {
// log.info("Looking into descriptor: {}", descriptor);
customizer.customize(descriptor);
}
}
}
......@@ -17,9 +17,6 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Account event contains the money / credit traffic for the user. Each row
* references a Product entity.
......@@ -27,7 +24,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "account_events")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class AccountEvent extends GenericEntity {
private static final long serialVersionUID = 2588419823225148100L;
......
......@@ -18,15 +18,12 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
import fi.codecrew.moya.enums.ActionLogMessageState;
@Entity
@Table(name = "actionlog_messages")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
@Table(name = "actionlog_messages")
public class ActionLogMessage extends GenericEntity {
private static final long serialVersionUID = -2902547412412000488L;
......
......@@ -12,14 +12,10 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import fi.codecrew.moya.enums.ActionLogMessageState;
@Entity
@Table(name = "actionlog_message_responses")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
@Table(name = "actionlog_message_responses")
public class ActionLogMessageResponse extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -5,13 +5,10 @@ import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
@Entity
@Table(name = "actionlog_message_tags")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class ActionLogMessageTag extends GenericEntity {
private static final long serialVersionUID = -2902547412412000488L;
......
......@@ -16,12 +16,8 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "api_applications")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class ApiApplication extends GenericEntity {
public static enum AuthType {
......
......@@ -8,15 +8,11 @@ import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import fi.codecrew.moya.enums.BortalApplication;
import fi.codecrew.moya.enums.apps.IAppPermission;
@Entity
@Table(name = "application_permissions", uniqueConstraints = { @UniqueConstraint(columnNames = { ApplicationPermission.ROLE_ID_COLUMN, ApplicationPermission.APPLICATION_COLUMN, ApplicationPermission.PERMISSION_COLUMN }) })
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class ApplicationPermission extends GenericEntity {
protected static final String APPLICATION_PERMISSION_CONVERTER = "application_permission_perm_typeconverter";
......
......@@ -20,8 +20,6 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -34,7 +32,6 @@ import fi.codecrew.moya.utilities.BillUtils;
*/
@Entity
@Table(name = "bills", uniqueConstraints = { @UniqueConstraint(columnNames = { Bill.EVENT_ID_COLUMN, "bill_number" }) })
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Bill extends GenericEntity {
/**
......
......@@ -16,15 +16,11 @@ import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "bill_lines")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class BillLine extends GenericEntity {
private static final long serialVersionUID = 2L;
......
......@@ -5,12 +5,8 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "card_code")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CardCode extends GenericEntity {
private static final long serialVersionUID = 307145499023412008L;
......@@ -29,10 +25,11 @@ public class CardCode extends GenericEntity {
@JoinColumn(name = "printed_cards_id")
private PrintedCard printedCard;
public CardCode(PrintedCard card, ReaderType type, String code) {
public CardCode(PrintedCard card, ReaderType type, String code, LanEvent event) {
this.printedCard = card;
this.type = type;
this.code = code;
this.event = event;
}
public CardCode() {
......
package fi.codecrew.moya.model;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import fi.codecrew.moya.enums.CardObjectDataType;
@Entity
@Table(name = "card_object_data")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CardObjectData extends GenericEntity {
private static final long serialVersionUID = 307145499023412008L;
@Column(name = "card_object_data_type", nullable = false)
@Enumerated(EnumType.STRING)
private CardObjectDataType objectDataType = CardObjectDataType.UNKNOWN;
@Column(name = "x", nullable = false)
private int x;
@Column(name = "y", nullable = false)
private int y;
@Column(name = "size", nullable = false, precision = 5, scale = 2)
private BigDecimal size;
@Column(name = "z_index", nullable = false)
private int zIndex;
@ManyToOne
@JoinColumn(nullable = false, name = "card_templates_id")
private CardTemplate cardTemplate;
public void setObjectDataType(CardObjectDataType field) {
this.objectDataType = field;
}
public CardObjectDataType getObjectDataType() {
return this.objectDataType;
}
public void setX(int x) {
this.x = x;
}
public int getX() {
return this.x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return this.y;
}
public void setSize(BigDecimal size) {
this.size = size;
}
public BigDecimal getSize() {
return this.size;
}
public void setZIndex(int z) {
this.zIndex = z;
}
public int getzIndex() {
return zIndex;
}
public void setzIndex(int zIndex) {
this.zIndex = zIndex;
}
public int getZIndex() {
return this.zIndex;
}
public void setCardTemplate(CardTemplate template) {
this.cardTemplate = template;
}
public CardTemplate getCardTemplate() {
return this.cardTemplate;
}
}
......@@ -15,15 +15,11 @@ import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* ID-card templates for the event.
*/
@Entity
@Table(name = "card_templates")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CardTemplate extends GenericEntity {
private static final long serialVersionUID = -5754760238181167610L;
......
package fi.codecrew.moya.model;
import java.awt.Color;
import java.awt.Font;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import fi.codecrew.moya.enums.CardTextAlignment;
import fi.codecrew.moya.enums.CardTextDataType;
import fi.codecrew.moya.enums.CardTextStyle;
@Entity
@Table(name = "card_text_data")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CardTextData extends GenericEntity{
private static final long serialVersionUID = 307145499023412008L;
@Column(name="card_text_data_type", nullable=false)
@Enumerated(EnumType.STRING)
private CardTextDataType textDataType = CardTextDataType.UNKNOWN;
@Column(name = "text_alignment", nullable = false)
@Enumerated(EnumType.STRING)
private CardTextAlignment textAlignment;
@Column(name = "x", nullable = false)
private int x;
@Column(name = "y", nullable = false)
private int y;
@Column(name = "size", nullable = false, precision = 5, scale = 2)
private BigDecimal size;
@Column(name = "font_color_r", nullable = false)
private int fontColorR;
@Column(name = "font_color_g", nullable = false)
private int fontColorG;
@Column(name = "font_color_b", nullable = false)
private int fontColorB;
@Column(name = "font_name", nullable = false)
private String fontName;
@Column(name = "font_style", nullable = false)
@Enumerated(EnumType.STRING)
private CardTextStyle fontStyle;
@Column(name = "text", nullable = true)
private String text;
@Column(name = "z_index", nullable = false)
private int zIndex;
@ManyToOne
@JoinColumn(nullable = false, name = "card_templates_id")
private CardTemplate cardTemplate;
public boolean isTypeStatic() {
if(this.textDataType == CardTextDataType.STATIC)
return true;
return false;
}
public void setTextDataType(CardTextDataType field) {
this.textDataType = field;
}
public CardTextDataType getTextDataType() {
return this.textDataType;
}
public void setX(int x) {
this.x = x;
}
public int getX() {
return this.x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return this.y;
}
public void setSize(BigDecimal size) {
this.size = size;
}
public BigDecimal getSize() {
return this.size;
}
public void setFontName(String font) {
this.fontName = font;
}
public String getFontName() {
return this.fontName;
}
public void setFontStyle(CardTextStyle fontStyle) {
this.fontStyle = fontStyle;
}
public CardTextStyle getFontStyle() {
return this.fontStyle;
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
public int getzIndex() {
return zIndex;
}
public void setzIndex(int zIndex) {
this.zIndex = zIndex;
}
public CardTextAlignment getTextAlignment() {
return textAlignment;
}
public void setTextAlignment(CardTextAlignment textAlignment) {
this.textAlignment = textAlignment;
}
public void setFont(Font font) {
//this.font = font;
this.fontName = font.getFontName();
this.size = new BigDecimal(font.getSize());
if(font.isBold() && font.isItalic())
this.fontStyle = CardTextStyle.BOLDITALIC;
else if(font.isItalic())
this.fontStyle = CardTextStyle.ITALIC;
else if(font.isPlain())
this.fontStyle = CardTextStyle.PLAIN;
}
public Font getFont() {
if(this.fontStyle == CardTextStyle.BOLD)
return new Font(this.fontName, Font.BOLD, this.size.intValue());
else if(this.fontStyle == CardTextStyle.ITALIC)
return new Font(this.fontName, Font.ITALIC, this.size.intValue());
else if(this.fontStyle == CardTextStyle.PLAIN)
return new Font(this.fontName, Font.PLAIN, this.size.intValue());
else
return new Font(this.fontName, Font.PLAIN, this.size.intValue());
}
public void setCardTemplate(CardTemplate template) {
this.cardTemplate = template;
}
public CardTemplate getCardTemplate() {
return this.cardTemplate;
}
public LanEvent getEvent() {
if(cardTemplate != null)
return cardTemplate.getEvent();
else
return null;
}
public int getFontColorR() {
return fontColorR;
}
public void setFontColorR(int fontColorR) {
this.fontColorR = fontColorR;
}
public int getFontColorG() {
return fontColorG;
}
public void setFontColorG(int fontColorG) {
this.fontColorG = fontColorG;
}
public int getFontColorB() {
return fontColorB;
}
public void setFontColorB(int fontColorB) {
this.fontColorB = fontColorB;
}
public void setFontColor(int r, int g, int b) {
this.fontColorR = r;
this.fontColorG = g;
this.fontColorB = b;
}
public String getColorHexCode() {
String r = Integer.toHexString(fontColorR);
String g = Integer.toHexString(fontColorG);
String b = Integer.toHexString(fontColorB);
return r + g + b;
}
public void setColorHexCode(String colorHexCode) {
Color color = null;
try {
color = Color.decode("#"+colorHexCode);
fontColorR = color.getRed();
fontColorG = color.getGreen();
fontColorB = color.getBlue();
}catch(Exception ex) {
}
}
}
......@@ -20,15 +20,11 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Competition to be held at the event.
*/
@Entity
@Table(name = "compos")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Compo extends GenericEntity {
private static final long serialVersionUID = 2L;
......
......@@ -20,15 +20,11 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "compo_entries")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CompoEntry extends GenericEntity {
private static final long serialVersionUID = 2L;
......
......@@ -21,8 +21,6 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.apache.commons.codec.binary.Hex;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -31,7 +29,6 @@ import org.slf4j.LoggerFactory;
*/
@Entity
@Table(name = "compo_entry_files")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CompoEntryFile extends GenericEntity {
private static final long serialVersionUID = 1L;
@Column(name = "mime_type")
......
......@@ -10,15 +10,11 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "compo_entry_participations")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CompoEntryParticipant extends GenericEntity {
private static final long serialVersionUID = 2L;
......
......@@ -22,39 +22,38 @@ public class DBModel implements ModelInterface {
@Id
@Column(name = ID_COLUMN, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer id;
@Column(name = "revision", nullable = false)
private Integer revision;
@Column(name = "revision", nullable = false)
private Integer revision;
@Column(name = "applied_at")
@Temporal(TemporalType.TIMESTAMP)
private Date appliedAt = new Date();
@Column(name = "applied_at")
@Temporal(TemporalType.TIMESTAMP)
private Date appliedAt = new Date();
@Override
public final Integer getId() {
return id;
}
@Override
public final Integer getId() {
return id;
}
@Override
public final void setId(Integer id) {
this.id = id;
}
@Override
public final void setId(Integer id) {
this.id = id;
}
public Date getAppliedAt() {
return appliedAt;
}
public Date getAppliedAt() {
return appliedAt;
}
public void setAppliedAt(Date appliedAt) {
this.appliedAt = appliedAt;
}
public void setAppliedAt(Date appliedAt) {
this.appliedAt = appliedAt;
}
public Integer getRevision() {
return revision;
}
public Integer getRevision() {
return revision;
}
public void setRevision(Integer revision) {
this.revision = revision;
}
public void setRevision(Integer revision) {
this.revision = revision;
}
}
......@@ -5,15 +5,11 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "discount_instances")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class DiscountInstance extends GenericEntity {
private static final long serialVersionUID = 2192672129232748522L;
......
......@@ -12,8 +12,6 @@ import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
/**
......@@ -21,7 +19,6 @@ import org.eclipse.persistence.annotations.PrivateOwned;
*/
@Entity
@Table(name = "maps")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class EventMap extends GenericEntity {
private static final long serialVersionUID = 3411450245513673619L;
......
......@@ -9,15 +9,11 @@ import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "event_organiser")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class EventOrganiser extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -26,14 +26,10 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import fi.codecrew.moya.enums.Gender;
@Entity
@Table(name = "event_users", uniqueConstraints = @UniqueConstraint(columnNames = { EventUser.USER_ID_COLUMN, EventUser.EVENT_ID_COLUMN }))
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class EventUser extends GenericEntity {
protected static final String USER_ID_COLUMN = "user_id";
......@@ -107,6 +103,10 @@ public class EventUser extends GenericEntity {
@OneToMany(mappedBy = "eventUser")
private List<GameID> gameIDs;
@ManyToMany(mappedBy = "participants")
private List<Lecture> lectures = new ArrayList<Lecture>();
public List<GameID> getGameIDs() {
return gameIDs;
......@@ -471,4 +471,15 @@ public class EventUser extends GenericEntity {
}
accountEvents.add(accountevent);
}
public List<Lecture> getLectures() {
if(lectures == null)
lectures = new ArrayList<Lecture>();
return lectures;
}
public void setLectures(List<Lecture> lectures) {
this.lectures = lectures;
}
}
......@@ -19,15 +19,11 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "food_waves")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class FoodWave extends GenericEntity {
private static final long serialVersionUID = 9221716203467295049L;
......
......@@ -18,15 +18,11 @@ import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "food_wave_templates")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class FoodWaveTemplate extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -6,8 +6,6 @@ import java.io.Serializable;
import javax.persistence.*;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Entity implementation class for Entity: GameID
......@@ -15,7 +13,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
*/
@Entity
@Table(name="game_ids")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class GameID extends GenericEntity implements Serializable {
private static final long serialVersionUID = 1L;
......
......@@ -13,34 +13,34 @@ import fi.codecrew.moya.utilities.jpa.ModelInterface;
@MappedSuperclass
public class GenericEntity extends EntityEquals implements ModelInterface, EntityMeta {
private static final long serialVersionUID = -9041737052951021560L;
public static final String ID_COLUMN = "id";
@Id
@Column(name = ID_COLUMN, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private JsonObject meta;
@Override
public final Integer getId() {
return id;
}
@Override
public final void setId(Integer id) {
this.id = id;
}
@Override
public JsonObject getMeta() {
return meta;
}
@Override
public void setMeta(JsonObject meta) {
this.meta = meta;
}
private static final long serialVersionUID = -9041737052951021560L;
public static final String ID_COLUMN = "id";
@Id
@Column(name = ID_COLUMN, nullable = false, updatable = false)
private Integer id;
@Column(name = "meta", columnDefinition = "json")
private JsonObject meta;
@Override
public final Integer getId() {
return id;
}
@Override
public final void setId(Integer id) {
this.id = id;
}
@Override
public JsonObject getMeta() {
return meta;
}
@Override
public void setMeta(JsonObject meta) {
this.meta = meta;
}
}
......@@ -4,6 +4,7 @@
*/
package fi.codecrew.moya.model;
import java.beans.Transient;
import java.util.Calendar;
import javax.persistence.CascadeType;
......@@ -16,9 +17,6 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
......@@ -26,7 +24,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@Table(name = "group_memberships")
// , uniqueConstraints = { @UniqueConstraint(columnNames = {
// GroupMembership.EVENTUSER_ID, GroupMembership.GROUP_ID }) })
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class GroupMembership extends GenericEntity {
/**
......
......@@ -10,12 +10,8 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "inventory_events")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
@Table(name = "inventory_events")
public class InventoryEvent extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -17,8 +17,6 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
import fi.codecrew.moya.enums.EventStatus;
......@@ -29,7 +27,6 @@ import fi.codecrew.moya.model.salespoint.Salespoint;
*/
@Entity
@Table(name = "events")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class LanEvent extends GenericEntity {
private static final long serialVersionUID = 179811358211927126L;
......
......@@ -7,12 +7,8 @@ import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "event_domains")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class LanEventDomain extends GenericEntity {
public LanEventDomain() {
......
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package fi.codecrew.moya.model;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Group for lectures, so you can set limits how many of these the user can choose
*/
@Entity
@Table(name = "lectures")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Lecture extends GenericEntity {
private static final long serialVersionUID = 3L;
@Column(name = "name")
private String name;
@Lob
@Column(name = "description")
private String description;
@ManyToOne
@JoinColumn(name = "lecture_group_id", referencedColumnName = LectureGroup.ID_COLUMN)
private LectureGroup lectureGroup;
@ManyToMany()
@JoinTable(name = "lecture_participants",
joinColumns = { @JoinColumn(name = "lecture_id", referencedColumnName = Lecture.ID_COLUMN) },
inverseJoinColumns = { @JoinColumn(name = "eventuser_id", referencedColumnName = EventUser.ID_COLUMN) })
private List<EventUser> participants;
@ManyToMany()
@JoinTable(name = "lecture_roles",
joinColumns = { @JoinColumn(name = "lecture_id", referencedColumnName = Lecture.ID_COLUMN) },
inverseJoinColumns = { @JoinColumn(name = "role_id", referencedColumnName = Role.ID_COLUMN) })
private List<Role> openForRoles;
@Column(name = "max_participants_count")
private Integer maxParticipantsCount;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "start_time")
private Calendar startTime;
@Column(name = "hours", precision = 10, scale = 2)
private BigDecimal hours;
public Lecture() {
super();
}
public Lecture(LectureGroup group) {
this();
setLectureGroup(group);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LectureGroup getLectureGroup() {
return lectureGroup;
}
public void setLectureGroup(LectureGroup lectureGroup) {
this.lectureGroup = lectureGroup;
}
public List<EventUser> getParticipants() {
if(participants == null)
participants = new ArrayList<EventUser>();
return participants;
}
public void setParticipants(List<EventUser> participants) {
this.participants = participants;
}
public List<Role> getOpenForRoles() {
if(openForRoles == null)
openForRoles = new ArrayList<Role>();
return openForRoles;
}
public void setOpenForRoles(List<Role> openForRoles) {
this.openForRoles = openForRoles;
}
public Integer getMaxParticipantsCount() {
return maxParticipantsCount;
}
public void setMaxParticipantsCount(Integer maxParticipantsCount) {
this.maxParticipantsCount = maxParticipantsCount;
}
public Calendar getStartTime() {
if(startTime == null) {
startTime = Calendar.getInstance();
}
return startTime;
}
public void setStartTime(Calendar startTime) {
this.startTime = startTime;
}
public Calendar getEndTime() {
if(getStartTime() == null || getHours() == null)
return getStartTime();
Calendar endTime = (Calendar) getStartTime().clone();
endTime.add(Calendar.MINUTE, getHours().multiply(new BigDecimal(60)).intValue());
return endTime;
}
public void setEndTime(Calendar endTime) {
if(endTime == null || getStartTime() == null) {
hours = BigDecimal.ZERO;
}
setHours(new BigDecimal((int) endTime.compareTo(getStartTime()) / 1000 / 60 / 60));
}
public BigDecimal getHours() {
return hours;
}
public void setHours(BigDecimal hours) {
this.hours = hours;
}
/**
* Clones lecture -object withoud database id and partisipants
*/
@Override
public Object clone() {
Lecture newLecture = new Lecture(this.getLectureGroup());
newLecture.setDescription(getDescription());
newLecture.setName(getName());
newLecture.setHours(getHours());
newLecture.setMaxParticipantsCount(getMaxParticipantsCount());
newLecture.setStartTime(getStartTime());
newLecture.setOpenForRoles(getOpenForRoles());
return newLecture;
}
@Transient
public boolean isFull() {
if(getMaxParticipantsCount() <= 0) {
return false;
}
return (getParticipants().size() >= getMaxParticipantsCount());
}
@Transient
public int getParticipantsCount() {
return getParticipants().size();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package fi.codecrew.moya.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Group for lectures, so you can set limits how many of these the user can choose
*/
@Entity
@Table(name = "lecture_groups")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class LectureGroup extends GenericEntity {
private static final long serialVersionUID = 4L;
@ManyToOne()
@JoinColumn(name = "event_id", nullable = false)
private LanEvent event;
@Column(name = "select_count")
private Integer selectCount;
@Column(name = "name")
private String name;
@Lob
@Column(name = "description")
private String description;
@OneToMany(mappedBy = "lectureGroup", cascade = CascadeType.ALL)
private List<Lecture> lectures;
public LectureGroup() {
super();
}
public LectureGroup(LanEvent event) {
this();
this.event = event;
}
public Integer getSelectCount() {
return selectCount;
}
public void setSelectCount(Integer selectCount) {
this.selectCount = selectCount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LanEvent getEvent() {
return event;
}
public void setEvent(LanEvent event) {
this.event = event;
}
public List<Lecture> getLectures() {
return lectures;
}
public void setLectures(List<Lecture> lectures) {
this.lectures = lectures;
}
}
......@@ -14,15 +14,11 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "licensecodes")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class LicenseCode extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -15,15 +15,11 @@ import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "licensetargets")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class LicenseTarget extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -13,9 +13,6 @@ import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
......@@ -26,7 +23,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
//
// @NamedQuery(name = "Location.findByLocationName", query =
// "SELECT l FROM Location l WHERE l.name = :name") })
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Location extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -16,15 +16,11 @@ import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "event_log")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class LogEntry extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -15,9 +15,6 @@ import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
......@@ -29,7 +26,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@NamedQuery(name = "LogEntryType.findAll", query = "SELECT l FROM LogEntryType l"),
@NamedQuery(name = "LogEntryType.findByName", query = "SELECT l FROM LogEntryType l WHERE l.name = :name"),
@NamedQuery(name = "LogEntryType.findByDescription", query = "SELECT l FROM LogEntryType l WHERE l.description = :description") })
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class LogEntryType extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -17,8 +17,6 @@ import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
import fi.codecrew.moya.enums.BortalApplication;
......@@ -30,7 +28,6 @@ import fi.codecrew.moya.enums.apps.IAppPermission;
MenuNavigation.ITEM_COLUMN,
MenuNavigation.EVENT_COLUMN })
})
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class MenuNavigation extends GenericEntity implements Comparable<MenuNavigation> {
private static final long serialVersionUID = 1404769998091479699L;
......
......@@ -9,13 +9,10 @@ import javax.persistence.Lob;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
@Entity
@Table(name = "menuitem")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Menuitem extends GenericEntity {
private static final long serialVersionUID = -3544095800802935237L;
......
package fi.codecrew.moya.model;
import java.util.Calendar;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import fi.codecrew.moya.enums.NetworkAssociationStatus;
@Entity
@Table(name = "network_associations")
public class NetworkAssociation extends GenericEntity {
private static final long serialVersionUID = -7621152614442737756L;
@JoinColumn(name="event")
private LanEvent event;
@JoinColumn(name="event_user")
private EventUser eventUser;
@Column(name="ip")
private String ip;
@Column(name="mac")
private String mac;
@JoinColumn(name="place")
private Place place;
@Column(name = "create_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Calendar createTime = Calendar.getInstance();
@Column(name = "modify_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Calendar modifyTime = Calendar.getInstance();
@Column(name="status", nullable = false)
@Enumerated(EnumType.STRING)
private NetworkAssociationStatus status;
public LanEvent getEvent() {
return event;
}
public void setEvent(LanEvent event) {
this.event = event;
}
public EventUser getEventUser() {
return eventUser;
}
public void setEventUser(EventUser eventUser) {
this.eventUser = eventUser;
}
public String getIP() {
return ip;
}
public String getIp() {
return ip;
}
public void setIP(String ip) {
this.ip = ip;
}
public String getMAC() {
return mac;
}
public String getMac() {
return mac;
}
public void setMAC(String mac) {
this.mac = mac;
}
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
public Calendar getCreateTime() {
return createTime;
}
public void setCreateTime(Calendar createTime) {
this.createTime = createTime;
}
public Calendar getModifyTime() {
return modifyTime;
}
public void setModifyTime(Calendar modifyTime) {
this.modifyTime = modifyTime;
}
public NetworkAssociationStatus getStatus() {
return status;
}
public void setStatus(NetworkAssociationStatus status) {
this.status = status;
}
}
......@@ -11,16 +11,12 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
* @author jkj
*/
@Entity
@Table(name = "news")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class News extends GenericEntity {
private static final long serialVersionUID = 498925968565236275L;
......
......@@ -18,8 +18,6 @@ import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
/**
......@@ -28,7 +26,6 @@ import org.eclipse.persistence.annotations.PrivateOwned;
*/
@Entity
@Table(name = "news_groups", uniqueConstraints = @UniqueConstraint(columnNames = { NewsGroup.EVENT_ID_COLUMN, NewsGroup.GROUP_NAME }))
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class NewsGroup extends GenericEntity {
protected static final String GROUP_NAME = "group_name";
......
......@@ -12,16 +12,12 @@ import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Entity implementation class for Entity: OrganizationalRole
*
*/
@Entity
@Table(name = "org_roles", uniqueConstraints = { @UniqueConstraint(columnNames = { OrgRole.EVENTORG_ID_COLUMN, OrgRole.NAME_COLUMN }) })
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class OrgRole extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -12,12 +12,8 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "site_page_content")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class PageContent extends GenericEntity {
private static final long serialVersionUID = 8359021214886290522L;
......
......@@ -12,17 +12,14 @@ import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import javax.persistence.Transient;
/**
*
*/
@Entity
@Table(name = "places")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Place extends GenericEntity {
public class Place extends GenericEntity implements Comparable<Place> {
/**
*
......@@ -278,4 +275,72 @@ public class Place extends GenericEntity {
this.disabled = disabled;
}
/**
* Note: this class has a natural ordering that is inconsistent with equals.
*/
@Override
@Transient
public int compareTo(Place o) {
if(this.getName().equals(o.getName())) {
return 0;
}
// check empty string etc.
if(o.getName().length() == 0) {
if(this.getName().length() > 0)
return 1;
return 0;
}
if(this.getName().length() == 0 && o.getName().length() > 0) {
return -1;
}
// check prefixes
String splitted[] = o.getName().split("[0-9]");
if(splitted[0].length() > 0) {
if(splitted[0].length() > this.getName().length()) {
return this.getName().compareTo(splitted[0]);
}
} else {
return 1;
}
String myPrefix = this.getName().substring(0, splitted[0].length());
if(myPrefix.compareTo(splitted[0]) != 0)
return myPrefix.compareTo(splitted[0]);
// prefixes are same, find numbers and check them
String otherNumber = o.getName().substring(splitted[0].length());
String myNumber = this.getName().substring(splitted[0].length());
try {
int other = Integer.parseInt(otherNumber);
int me = Integer.parseInt(myNumber);
if(other < me) {
return 1;
}
if(other > me)
return -1;
return 0;
} catch(NumberFormatException x) {
return myNumber.compareTo(otherNumber);
}
}
}
......@@ -20,15 +20,11 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "groups")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class PlaceGroup extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -18,16 +18,12 @@ import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Temporal;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Entity implementation class for Entity: Poll
*
*/
@Entity
@Table(name = "poll")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Poll extends GenericEntity {
/**
......
......@@ -9,12 +9,8 @@ import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "poll_answer")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class PollAnswer extends GenericEntity implements Serializable {
/**
......
......@@ -13,12 +13,8 @@ import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "poll_question")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class PollQuestion extends GenericEntity {
public PollQuestion() {
......
......@@ -11,12 +11,8 @@ import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "possible_answer")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class PossibleAnswer extends GenericEntity {
public PossibleAnswer() {
......
......@@ -25,9 +25,6 @@ import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import fi.codecrew.moya.enums.CardState;
/**
......@@ -37,7 +34,6 @@ import fi.codecrew.moya.enums.CardState;
@Table(name = "printed_cards", uniqueConstraints = {
@UniqueConstraint(columnNames = { "event_id", "rfid_uid", }),
@UniqueConstraint(columnNames = { "event_id", "barcode" }) })
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class PrintedCard extends GenericEntity {
private static final long serialVersionUID = 8603481931116401027L;
......
......@@ -27,8 +27,6 @@ import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
/**
......@@ -36,7 +34,6 @@ import org.eclipse.persistence.annotations.PrivateOwned;
*/
@Entity
@Table(name = "products")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Product extends GenericEntity {
private static final String PRODUCTFLAG_TABLE_PRODUCTID = "product_id";
......
......@@ -11,12 +11,8 @@ import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "product_limitations")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class ProductLimitation extends GenericEntity {
/**
......
......@@ -25,9 +25,6 @@ import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import fi.codecrew.moya.model.salespoint.SalesEntity;
/**
......@@ -35,7 +32,6 @@ import fi.codecrew.moya.model.salespoint.SalesEntity;
*/
@Entity
@Table(name = "readers", uniqueConstraints = { @UniqueConstraint(columnNames = { "reader_ident", "event_id" }) })
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Reader extends GenericEntity {
public Reader(LanEvent ev, String ident) {
......
......@@ -14,15 +14,11 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "reader_events")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class ReaderEvent extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -14,8 +14,6 @@ import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
/**
......@@ -23,7 +21,6 @@ import org.eclipse.persistence.annotations.PrivateOwned;
*/
@Entity
@Table(name = "roles", uniqueConstraints = { @UniqueConstraint(columnNames = { Role.EVENT_ID_COLUMN, Role.NAME_COLUMN }) })
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Role extends GenericEntity {
private static final long serialVersionUID = -4602863502464505404L;
......@@ -85,6 +82,11 @@ public class Role extends GenericEntity {
joinColumns = { @JoinColumn(name = "role_id", referencedColumnName = Role.ID_COLUMN) },
inverseJoinColumns = { @JoinColumn(name = "org_role_id", referencedColumnName = OrgRole.ID_COLUMN) })
private List<OrgRole> orgRoles;
@ManyToMany(mappedBy = "openForRoles")
private List<Lecture> lectures = new ArrayList<Lecture>();
public Role() {
super();
......@@ -209,6 +211,7 @@ public class Role extends GenericEntity {
this.orgRoles = orgRoles;
}
public int getSelectChildrensCount() {
return selectChildrensCount;
}
......@@ -217,4 +220,13 @@ public class Role extends GenericEntity {
this.selectChildrensCount = selectChildrensCount;
}
public List<Lecture> getLectures() {
return lectures;
}
public void setLectures(List<Lecture> lectures) {
this.lectures = lectures;
}
}
......@@ -12,13 +12,10 @@ import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
@Entity
@Table(name = "site_pages", uniqueConstraints = @UniqueConstraint(columnNames = { SitePage.EVENT_ID_COLUMN, "name" }))
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class SitePage extends GenericEntity {
private static final long serialVersionUID = -4333555423866132524L;
......
......@@ -9,8 +9,6 @@ import java.util.List;
import javax.persistence.*;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Entity implementation class for Entity: Tournament
......@@ -18,7 +16,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
*/
@Entity
@Table(name="tournaments")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Tournament extends GenericEntity implements Serializable {
private static final long serialVersionUID = 1L;
......
......@@ -9,8 +9,6 @@ import java.util.List;
import javax.persistence.*;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Entity implementation class for Entity: Tournament
......@@ -18,7 +16,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
*/
@Entity
@Table(name="tournament_games")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class TournamentGame extends GenericEntity implements Serializable {
private static final long serialVersionUID = 1L;
......
......@@ -8,8 +8,6 @@ import java.util.List;
import javax.persistence.*;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Entity implementation class for Entity: Match
......@@ -17,7 +15,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
*/
@Entity
@Table(name="matches")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class TournamentMatch extends GenericEntity implements Serializable {
private static final long serialVersionUID = 1L;
......
......@@ -3,8 +3,6 @@ package fi.codecrew.moya.model;
import java.io.Serializable;
import javax.persistence.*;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Entity implementation class for Entity: MatchResult
......@@ -12,7 +10,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
*/
@Entity
@Table(name="match_results")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class TournamentMatchResult extends GenericEntity implements Serializable {
private static final long serialVersionUID = 1L;
......
......@@ -6,8 +6,6 @@ import java.util.List;
import javax.persistence.*;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Entity implementation class for Entity: TournamentParticipant
......@@ -15,7 +13,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
*/
@Entity
@Table(name="tournament_participants")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class TournamentParticipant extends GenericEntity implements Serializable {
private static final long serialVersionUID = 1L;
......
......@@ -9,8 +9,6 @@ import java.util.List;
import javax.persistence.*;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* Entity implementation class for Entity: Tournament
......@@ -18,7 +16,6 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
*/
@Entity
@Table(name="tournament_rules")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class TournamentRule extends GenericEntity implements Serializable {
private static final long serialVersionUID = 1L;
......
......@@ -10,14 +10,10 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import fi.codecrew.moya.enums.TournamentTeamMemberRole;
@Entity
@Table(name="tournament_team_members")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class TournamentTeamMember extends GenericEntity implements Serializable {
private static final long serialVersionUID = 8511689754953929329L;
......
......@@ -19,15 +19,11 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
*/
@Entity
@Table(name = "user_images")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class UserImage extends GenericEntity {
private static final long serialVersionUID = 1L;
......
......@@ -16,15 +16,11 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
* A vote for a compo entry
*/
@Entity
@Table(name = "compo_votes", uniqueConstraints = { @UniqueConstraint(columnNames = { Vote.ENTRY_ID, Vote.VOTER_USER_ID }) })
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Vote extends GenericEntity {
protected static final String VOTER_USER_ID = "voter_userevent_id";
......
......@@ -10,45 +10,64 @@ import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import org.postgresql.util.PGobject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Converter(autoApply = true)
public class JsonAttributeConverter implements AttributeConverter<JsonObject, PGobject> {
private static final Logger log = LoggerFactory.getLogger(JsonAttributeConverter.class);
public PGobject convertToDatabaseColumn(JsonObject attribute) {
if (attribute == null) {
return null;
}
/**
* JsonObject -> PGobject
*/
public PGobject convertToDatabaseColumn(JsonObject jsonObject) {
log.info("Converting JsonObject to PGobject. Original JsonObject: {}", jsonObject);
final PGobject dataValue = new PGobject();
dataValue.setType("json");
PGobject pgObject = new PGobject();
pgObject.setType("json");
try {
if (jsonObject != null) {
pgObject.setValue(jsonObject.toString());
} else {
pgObject.setValue(null);
}
} catch (SQLException e) {
log.warn("PGobject.setValue() threw an exception. Should not happen. Something is wrong.", e);
}
log.info("Converted JsonObject to PGobject: {}", pgObject);
return pgObject;
}
try {
dataValue.setValue(attribute.toString());
} catch (SQLException e) {
// This will never run because PGobject.setValue() cannot really
// throw an SQLException. There is nothing but setting a property.
throw new RuntimeException("THIS SHOULD NEVER HAPPEN", e);
}
/**
* PGobject -> JsonObject
*/
public JsonObject convertToEntityAttribute(PGobject pgObject) {
log.info("Converting PGobject to JsonObject. Original PGobject: {}", pgObject);
return dataValue;
}
// Convert null values to empty object
if (pgObject == null) {
log.info("PGobject was null. Retruning an empty JsonObject.");
return Json.createObjectBuilder().build();
}
public JsonObject convertToEntityAttribute(PGobject dbData) {
// Has any?
if (dbData == null) {
return null;
}
// Correct type of object?
if (dbData.getType().equals("json") == false) {
throw new RuntimeException("Expected JSON object from database");
}
// Read as JSON object
final StringReader stringReader = new StringReader(dbData.getValue());
final JsonReader jsonReader = Json.createReader(stringReader);
return jsonReader.readObject();
}
// Correct type of object?
if (pgObject.getType().equals("json") == false) {
log.error("Expected to be converting JSON column, but got PGobject whose type is not json but {}", pgObject.getType());
throw new RuntimeException("Expected JSON object from database");
}
// Read the value as JSON
String stringValue = pgObject.getValue();
// We must test for "null" because pgObject.getValues() seems to return "null" for null :)
if (stringValue != null && !stringValue.toLowerCase().equals("null")) {
JsonReader jsonReader = Json.createReader(new StringReader(stringValue));
JsonObject jsonObject = jsonReader.readObject();
log.info("Converted PGobject to JsonObject: {}", jsonObject);
return jsonObject;
} else {
log.info("Null value. Returning empty JsonObject");
return Json.createObjectBuilder().build();
}
}
}
......@@ -26,7 +26,10 @@
<dependent-module archiveName="org.ancoron.postgresql.jpa-9.1.901.jdbc4.1-rc9.jar" deploy-path="/lib" handle="module:/classpath/var/M2_REPO/org/ancoron/postgresql/org.ancoron.postgresql.jpa/9.1.901.jdbc4.1-rc9/org.ancoron.postgresql.jpa-9.1.901.jdbc4.1-rc9.jar">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module archiveName="postgresql-9.3-1100-jdbc41.jar" deploy-path="/lib" handle="module:/classpath/var/M2_REPO/org/postgresql/postgresql/9.3-1100-jdbc41/postgresql-9.3-1100-jdbc41.jar">
<dependent-module archiveName="postgresql-9.3-1101-jdbc41.jar" deploy-path="/lib" handle="module:/classpath/var/M2_REPO/org/postgresql/postgresql/9.3-1101-jdbc41/postgresql-9.3-1101-jdbc41.jar">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module archiveName="org.postgresql.net-9.1.901.jdbc4.1-rc9.jar" deploy-path="/lib" handle="module:/classpath/var/M2_REPO/org/ancoron/postgresql/org.postgresql.net/9.1.901.jdbc4.1-rc9/org.postgresql.net-9.1.901.jdbc4.1-rc9.jar">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module archiveName="pdfjet-0.0.0-2013-08-19.jar" deploy-path="/lib" handle="module:/classpath/var/M2_REPO/fi/iudex/pdfjet/pdfjet/0.0.0-2013-08-19/pdfjet-0.0.0-2013-08-19.jar">
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!