Commit 2afbe690 by Liv Haapala

Merge branch 'master' of gitlab.codecrew.fi:codecrew/moya

Conflicts:
	code/MoyaWeb/WebContent/useradmin/list.xhtml
2 parents 2c78c6fc 2fb04eec
Showing with 2397 additions and 1133 deletions
......@@ -7,3 +7,4 @@
*~
.metadata
/code/*/target/
/code/*/test-output/
No preview for this file type
......@@ -86,13 +86,14 @@ public class MoyaLoginModule extends AppservPasswordLoginModule {
// Authenticate User
MoyaRealm samplerealm = (MoyaRealm) _currentRealm;
if (!authbean.authenticate(_username, new String(_passwd))) {
AuthenticationResult authResult = authbean.authUsername(_username, new String(_passwd));
if (authResult == null || authResult.getUsername() == null) {
// Login fails
throw new LoginException((new StringBuilder())
.append("moya realm:Login Failed for user ")
.append(_username).toString());
}
_username = authResult.getUsername();
// Login succeeds
log((new StringBuilder()).append("MoyaRealm:login succeeded for ")
.append(_username).toString());
......@@ -100,7 +101,7 @@ public class MoyaLoginModule extends AppservPasswordLoginModule {
// Get group names for the authenticated user from the Realm class
Enumeration<String> enumeration = null;
try {
enumeration = samplerealm.getGroupNames(_username);
enumeration = samplerealm.getGroupNames(_username, authResult.getUsertype());
} catch (InvalidOperationException invalidoperationexception) {
throw new LoginException(
(new StringBuilder())
......
......@@ -89,7 +89,7 @@ public class MoyaRealm extends AppservRealm {
*/
@Override
public String getAuthType() {
return "Omnia Lan system authentication Realm";
return "Moya authentication Realm";
}
/**
......@@ -127,4 +127,8 @@ public class MoyaRealm extends AppservRealm {
}
public Enumeration<String> getGroupNames(String username, String usertype) throws InvalidOperationException, NoSuchUserException {
return getAuthBean().getGroupNames(username, usertype);
}
}
package fi.codecrew.moya;
public class AuthenticationResult {
private String username = null;
private String usertype = null;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
}
......@@ -13,4 +13,8 @@ public interface MoyaRealmBeanRemote {
boolean authenticate(String _username, String string);
AuthenticationResult authUsername(String _username, String string);
Enumeration<String> getGroupNames(String username, String usertype);
}
......@@ -36,6 +36,31 @@ public class BootstrapBean implements BootstrapBeanLocal {
dbUpdates.add(new String[] { "ALTER TABLE products ALTER COLUMN vat TYPE NUMERIC(4,3)" });
dbUpdates.add(new String[] { "ALTER TABLE actionlog_messages DROP COLUMN crew" });
dbUpdates.add(new String[] { "delete from application_permissions where application ilike '%terminal%'" });
dbUpdates.add(new String[] {
"ALTER TABLE org_roles ADD ldap_role boolean not null default false",
"ALTER TABLE org_roles ADD ldap_weight integer NOT NULL default 100"
});
// barcodefuckup
dbUpdates.add(new String[] {
"DROP TABLE card_barcode",
"ALTER TABLE printed_cards DROP COLUMN barcode;",
"ALTER TABLE printed_cards DROP COLUMN rfid_uid;",
"ALTER TABLE reader_events ADD COLUMN event_users_id integer REFERENCES event_users(id) DEFAULT null;",
"ALTER TABLE reader_events ADD COLUMN places_id integer REFERENCES places(id) DEFAULT null;",
"ALTER TABLE reader_events ADD COLUMN products_id integer REFERENCES products(id) DEFAULT null;",
"ALTER TABLE reader_events ADD COLUMN type text NOT NULL DEFAULT 'UNKNOWN';",
"ALTER TABLE reader_events DROP COLUMN gamepoint;",
"ALTER TABLE reader_events ALTER COLUMN type DROP DEFAULT;",
});
dbUpdates.add(new String[] {
"delete from menu_navigation where item_id in (select id from menuitem where url in ( '/actionlog/messagelist'))",
"delete from menuitem where url in ('/actionlog/messagelist')",
});
dbUpdates.add(new String[] {
"alter table compos add hidden boolean default false not null"
});
}
@EJB
......@@ -61,7 +86,8 @@ public class BootstrapBean implements BootstrapBeanLocal {
throw new RuntimeException("Sanity check failed! DB is newer than the codebase!");
}
} else {
// DB is up to date by default! We need to mark the current version down though.
// DB is up to date by default! We need to mark the current version
// down though.
dBm = new DBModel();
dBm.setRevision(upIdx);
dbModelFacade.create(dBm);
......
......@@ -189,10 +189,10 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
public CardTemplate getUsersCardtype(EventUser user) {
Set<Role> roles = userbean.localFindUsersRoles(user);
logger.info("Checking roles {} against {}", user, roles);
// logger.info("Checking roles {} against {}", user, roles);
CardTemplate greatestTemplate = null;
for (Role listrole : roles) {
logger.info("Checking role {}", listrole);
// logger.info("Checking role {}", listrole);
if (greatestTemplate == null || (listrole.getCardTemplate() != null && greatestTemplate.getPower() < listrole.getCardTemplate().getPower())) {
greatestTemplate = listrole.getCardTemplate();
}
......
......@@ -138,7 +138,7 @@ public class EventBean implements EventBeanLocal {
@Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT })
public LanEvent mergeChanges(LanEvent event) {
if (!permbean.hasPermission(SpecialPermission.SUPERADMIN) && getCurrentEvent().equals(event)) {
if (!permbean.hasPermission(SpecialPermission.SUPERADMIN) && !getCurrentEvent().equals(event)) {
throw new EJBAccessException("Trying to save another event.");
}
return eventFacade.merge(event);
......@@ -187,8 +187,7 @@ public class EventBean implements EventBeanLocal {
public LanEventProperty getProperty(LanEventPropertyKey property) {
return eventPropertyFacade.find(getCurrentEvent(), property);
}
@Override
public long getPropertyLong(LanEventPropertyKey property)
{
......@@ -201,8 +200,6 @@ public class EventBean implements EventBeanLocal {
}
return ret;
}
@Override
public String getPropertyString(LanEventPropertyKey property)
......@@ -266,4 +263,33 @@ public class EventBean implements EventBeanLocal {
return ret;
}
/**
* If you want this event, user getCurrentEvent() This method should be used
* only in special cases...
*/
@Override
@RolesAllowed(EventPermission.S_MANAGE_EVENT)
public LanEvent getEventById(Integer id) {
return eventFacade.find(id);
}
@Override
@RolesAllowed(EventPermission.S_MANAGE_EVENT)
public LanEvent deleteProperty(LanEventProperty property) {
property = eventPropertyFacade.reload(property);
LanEvent event = property.getEvent();
event.getProperties().remove(property);
eventPropertyFacade.refresh(property);
return event;
}
@Override
@RolesAllowed({ EventPermission.S_MANAGE_PRIVATE_PROPERTIES, EventPermission.S_MANAGE_EVENT })
public LanEvent deletePrivateProperty(LanEventPrivateProperty property) {
LanEventPrivateProperty prop = eventPrivatePropertyFacade.reload(property);
LanEvent event = prop.getEvent();
eventPrivatePropertyFacade.remove(property);
return event;
}
}
......@@ -109,4 +109,12 @@ public class EventMapBean implements EventMapBeanLocal {
public Place updatePlace(Place place) {
return placefacade.merge(place);
}
@Override
@RolesAllowed(MapPermission.S_MANAGE_MAPS)
public void createPlace(Place place) {
EventMap map = eventmapfacade.reload(place.getMap());
map.getPlaces().add(place);
place.setMap(map);
}
}
......@@ -11,18 +11,26 @@ import javax.ejb.Stateless;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.AuthenticationResult;
import fi.codecrew.moya.MoyaRealmBeanRemote;
import fi.codecrew.moya.enums.BortalApplication;
import fi.codecrew.moya.enums.apps.IAppPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.facade.ApiApplicationFacade;
import fi.codecrew.moya.facade.ApiApplicationInstanceFacade;
import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.facade.UserFacade;
import fi.codecrew.moya.model.ApiApplication;
import fi.codecrew.moya.model.ApiApplicationInstance;
import fi.codecrew.moya.model.ApplicationPermission;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.LanEventProperty;
import fi.codecrew.moya.model.LanEventPropertyKey;
import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.utilities.PasswordFunctions;
/**
* Session Bean implementation class SessionHandlerBean
......@@ -48,6 +56,15 @@ public class JaasBean implements MoyaRealmBeanRemote {
@EJB
private EventBeanLocal eventbean;
@EJB
private RestBean restbean;
@EJB
private ApiApplicationFacade appfacade;
@EJB
private ApiApplicationInstanceFacade appInstanceFacade;
@EJB
private EventBean eventorgbean;
public EventUser tryLogin(String username, String password) {
EventUser eventUser = eventUserFacade.findByLogin(username.trim().toLowerCase());
......@@ -69,7 +86,13 @@ public class JaasBean implements MoyaRealmBeanRemote {
eventUser = null;
user = null;
}
if (user != null && eventUser == null)
LanEventProperty inviteonly = eventbean.getProperty(LanEventPropertyKey.INVITE_ONLY_EVENT);
boolean createEventuser = true;
if (inviteonly != null && inviteonly.isBooleanValue()) {
createEventuser = false;
}
if (createEventuser && user != null && eventUser == null)
{
LanEvent event = eventbean.getCurrentEvent();
eventUser = new EventUser(user, event, null);
......@@ -97,15 +120,45 @@ public class JaasBean implements MoyaRealmBeanRemote {
// }
// }
public static enum UserType
{
USER, REST
}
@Override
public boolean authenticate(String username, String password) {
boolean ret = (tryLogin(username, password) != null);
public AuthenticationResult authUsername(String username, String password) {
AuthenticationResult ret = new AuthenticationResult();
ret.setUsertype(UserType.USER.name());
if ((username == null || username.isEmpty()) && password.startsWith("rest:")) {
ret.setUsertype(UserType.REST.name());
ret.setUsername(restAuth(password));
} else {
EventUser retUser = tryLogin(username, password);
if (retUser != null) {
ret.setUsername(retUser.getLogin());
}
}
return ret;
}
@Override
public Enumeration<String> getGroupNames(String user) {
logger.info("Fetching groupNames for user {} event {}", user, eventbean.getCurrentEvent().getName());
public boolean authenticate(String username, String password) {
return (tryLogin(username, password) != null);
}
private String restAuth(String restauth) {
String[] authsplit = restauth.split(":");
if (authsplit.length != 6 || !authsplit[0].equals("rest")) {
return null;
}
return authenticateApp(authsplit[1], authsplit[2], authsplit[3], authsplit[4], authsplit[5]);
}
@Override
public Enumeration<String> getGroupNames(String user, String usertype) {
EventUser usr = eventUserFacade.findByLogin(user.toLowerCase().trim());
HashSet<String> roleset = new HashSet<String>();
roleset.add(UserPermission.ANYUSER.getFullName());
......@@ -119,6 +172,23 @@ public class JaasBean implements MoyaRealmBeanRemote {
roleset.add(SpecialPermission.ANONYMOUS.name());
}
if (usertype != null) {
try {
switch (UserType.valueOf(usertype))
{
case REST:
roleset.add(SpecialPermission.REST.name());
break;
case USER:
break;
default:
throw new RuntimeException("Unknown user type: " + usertype);
}
} catch (Throwable t) {
logger.warn("UserType authentication " + usertype);
}
}
if (!usr.getUser().isAnonymous()) {
// all logged in users should be able to logout :)
roleset.add(UserPermission.LOGOUT.name());
......@@ -152,8 +222,46 @@ public class JaasBean implements MoyaRealmBeanRemote {
Vector<String> retvect = new Vector<String>();
retvect.addAll(roleset);
logger.info("group names for user {}: {}", user, retvect);
logger.debug("group names for user {}: {}", user, retvect);
return retvect.elements();
}
@Override
public Enumeration<String> getGroupNames(String username) {
return getGroupNames(username, null);
}
public String authenticateApp(String pathInfo, String appId, String userId, String appStamp, String mac) {
if (mac == null)
return null;
ApiApplication app = appfacade.findByAppid(appId);
if (app == null)
return null;
ApiApplicationInstance apiInstance = appInstanceFacade.findInstance(app, userId);
if (apiInstance == null)
return null;
if (!app.isEnabled() || !apiInstance.isEnabled())
return null;
String ret = null;
String macSource = PasswordFunctions.mkSeparatedString("+", pathInfo, appId, userId, appStamp, apiInstance.getSecretKey());
String macHash = PasswordFunctions.calculateSha1(macSource);
if (mac.equalsIgnoreCase(macHash))
{
switch (app.getAuthtype()) {
case ORGAUTH:
ret = User.ANONYMOUS_LOGINNAME;
break;
case USERKEY:
if (apiInstance.getEventuser() != null) {
ret = apiInstance.getEventuser().getUser().getLogin();
}
break;
default:
throw new RuntimeException("Unknown application authtype!");
}
}
return ret;
}
}
package fi.codecrew.moya.beans;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import fi.codecrew.moya.beanutil.LdapUserHandler;
import fi.codecrew.moya.model.LanEventPrivatePropertyKey;
/**
* Session Bean implementation class LdapBean
*/
@Stateless
@LocalBean
public class LdapBean implements LdapBeanLocal {
@EJB
private EventBean eventbean;
/**
* Default constructor.
*/
public LdapConnection getConnection() {
String ldapurl = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.LDAP_URL);
String userBase = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.LDAP_USER_OU);
String groupBase = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.LDAP_GROUP_OU);
LdapConnection conn = null;
if (ldapurl != null && !ldapurl.isEmpty() && userBase != null && !userBase.isEmpty() && groupBase != null && !groupBase.isEmpty()) {
String bindDn = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.LDAP_BIND_DN);
String bindPw = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.LDAP_BIND_PW);
conn = new LdapConnection(ldapurl, userBase, groupBase, bindDn, bindPw);
}
return conn;
}
private static class LdapConnection extends LdapUserHandler
{
public LdapConnection(String ldapUri, String userBaseDn, String groupBaseDn, String mgmtUser, String mgmtPass) {
super(ldapUri, userBaseDn, groupBaseDn, mgmtUser, mgmtPass);
}
}
}
......@@ -20,6 +20,7 @@ import fi.codecrew.moya.enums.apps.MapPermission;
import fi.codecrew.moya.enums.apps.PollPermission;
import fi.codecrew.moya.enums.apps.ShopPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.enums.apps.TerminalPermission;
import fi.codecrew.moya.enums.apps.TournamentPermission;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.facade.MenuNavigationFacade;
......@@ -27,8 +28,17 @@ import fi.codecrew.moya.facade.MenuitemFacade;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.MenuNavigation;
// *************************************************
// *** LUE TÄMÄ ENNEN KUN TEET MUUTOKSIA MENUUN! **
// *************************************************
/**
* Session Bean implementation class Menubean
*
* 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).
*
*
*/
@Stateless
@LocalBean
......@@ -70,7 +80,7 @@ public class MenuBean implements MenuBeanLocal {
private synchronized void initializeMenu() {
//int menusort = 100;
// int menusort = 100;
logger.info("Initializing new default menu");
LanEvent ev = eventbean.getCurrentEvent();
......@@ -83,9 +93,9 @@ public class MenuBean implements MenuBeanLocal {
usermenu.addPage(menuitemfacade.findOrCreate("/checkout/cancel"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/permissionDenied"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/utils/flushCache"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/login"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/loginError"), null).setVisible(false);
// usermenu.addPage(menuitemfacade.findOrCreate("/auth/logout"), null).setVisible(false); // disabled
usermenu.addPage(menuitemfacade.findOrCreate("/auth/logoutResponse"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/resetPassword"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/resetmailSent"), null).setVisible(false);
......@@ -105,12 +115,15 @@ public class MenuBean implements MenuBeanLocal {
userkauppa.addPage(menuitemfacade.findOrCreate("/shop/createBill"), BillPermission.CREATE_BILL);
userkauppa.addPage(menuitemfacade.findOrCreate("/foodwave/list"), ShopPermission.SHOP_FOODWAVE);
userkauppa.addPage(menuitemfacade.findOrCreate("/bill/list"), BillPermission.VIEW_OWN);
userkauppa.addPage(menuitemfacade.findOrCreate("/user/accountEvents"), UserPermission.VIEW_ACCOUNTEVENTS);
userkauppa.addPage(menuitemfacade.findOrCreate("/bill/edit"), BillPermission.VIEW_OWN).setVisible(false);
userkauppa.addPage(menuitemfacade.findOrCreate("/bill/showBill"), BillPermission.VIEW_OWN).setVisible(false);
userkauppa.addPage(menuitemfacade.findOrCreate("/user/accountEvents"), UserPermission.VIEW_OWN_ACCOUNTEVENTS);
MenuNavigation userPlaces = usermenu.addPage(null, null);
userPlaces.setKey("topnavi.userplaces");
userPlaces.addPage(menuitemfacade.findOrCreate("/place/placemap"), MapPermission.VIEW);
userPlaces.addPage(menuitemfacade.findOrCreate("/place/myGroups"), MapPermission.BUY_PLACES);
userPlaces.addPage(menuitemfacade.findOrCreate("/place/edit"), MapPermission.MANAGE_OTHERS).setVisible(false);
MenuNavigation usercompetitions = usermenu.addPage(null, null);
usercompetitions.setKey("topnavi.competitions");
......@@ -137,12 +150,10 @@ public class MenuBean implements MenuBeanLocal {
tournaments.addPage(menuitemfacade.findOrCreate("/tournaments/participate_multi"), TournamentPermission.PARTICIPATE).setVisible(false);
tournaments.addPage(menuitemfacade.findOrCreate("/tournaments/addTeam"), TournamentPermission.PARTICIPATE).setVisible(false);
/*
* MenuNavigation createuser = usermenu.addPage(null, null);
* createuser.setKey("topnavi.createuser");
* createuser.addPage(menuitemfacade.findOrCreate("/user/create"),
* UserPermission.CREATE_NEW);
*/
MenuNavigation createuser = usermenu.addPage(null, null);
createuser.setKey("topnavi.createuser");
createuser.addPage(menuitemfacade.findOrCreate("/user/create"), UserPermission.CREATE_NEW).setVisible(false);
;
navifacade.create(usermenu);
......@@ -152,7 +163,7 @@ public class MenuBean implements MenuBeanLocal {
MenuNavigation adminmenu = new MenuNavigation(ev, "topmenu.admin", 20);
//user management
// user management
MenuNavigation adminuser = adminmenu.addPage(null, null);
adminuser.setKey("topnavi.usermgmt");
adminuser.addPage(menuitemfacade.findOrCreate("/useradmin/list"), UserPermission.VIEW_ALL);
......@@ -193,7 +204,6 @@ public class MenuBean implements MenuBeanLocal {
adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/list"), ShopPermission.LIST_ALL_PRODUCTS);
adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/create"), ShopPermission.MANAGE_PRODUCTS);
adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/edit"), ShopPermission.MANAGE_PRODUCTS).setVisible(false);
;
MenuNavigation foodnavi = adminshop.addPage(null, null);
foodnavi.setKey("topnavi.foodwave");
......@@ -219,7 +229,8 @@ public class MenuBean implements MenuBeanLocal {
MenuNavigation adminPlaces = adminmenu.addPage(null, null);
adminPlaces.setKey("topnavi.userplaces");
adminPlaces.addPage(menuitemfacade.findOrCreate("/place/adminPlacemap"), UserPermission.VIEW_ALL);
// adminPlaces.addPage(menuitemfacade.findOrCreate("/place/adminGroups"), UserPermission.VIEW_ALL); // todo: make new view for managing
// adminPlaces.addPage(menuitemfacade.findOrCreate("/place/adminGroups"),
// UserPermission.VIEW_ALL); // todo: make new view for managing
MenuNavigation mapnavi = adminPlaces.addPage(null, null);
mapnavi.setKey("topnavi.maps");
......@@ -253,13 +264,7 @@ public class MenuBean implements MenuBeanLocal {
gamenavi.addPage(menuitemfacade.findOrCreate("/license/manageCodes"), LicensePermission.MANAGE);
adminevent.addPage(menuitemfacade.findOrCreate("/eventorg/editEvent"), EventPermission.MANAGE_PROPERTIES);
navifacade.create(adminmenu);
//MenuNavigation shopmenu = new MenuNavigation(ev, "topnavi.shopnavi", menusort = +10);
// shopnavi.addPage(menuitemfacade.findOrCreate("/index3"),
// UserPermission.ANYUSER);
// navifacade.create(shopmenu);
adminevent.addPage(menuitemfacade.findOrCreate("/eventorg/edit"), EventPermission.MANAGE_PROPERTIES).setVisible(false);
MenuNavigation tournamentsadm = adminmenu.addPage(null, null);
tournamentsadm.setKey("tournaments.menutitle");
......@@ -270,6 +275,24 @@ public class MenuBean implements MenuBeanLocal {
tournamentsadm.addPage(menuitemfacade.findOrCreate("/tournaments/admin/edit"), TournamentPermission.MANAGE_ALL).setVisible(false);
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 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);
navifacade.create(adminmenu);
// MenuNavigation shopmenu = new MenuNavigation(ev, "topnavi.shopnavi",
// menusort = +10);
// shopnavi.addPage(menuitemfacade.findOrCreate("/index3"),
// UserPermission.ANYUSER);
// navifacade.create(shopmenu);
/*
* MenuNavigation profileTopmenu = new MenuNavigation(ev,
* "topnavi.profile", menusort = +10);
......@@ -330,6 +353,36 @@ public class MenuBean implements MenuBeanLocal {
}
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// OLD MENU STARTS HERE!!!
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
private synchronized void initializeOldMenu() {
LanEvent ev = eventbean.getCurrentEvent();
......@@ -346,6 +399,7 @@ public class MenuBean implements MenuBeanLocal {
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/sendResetMail"), UserPermission.LOGIN);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/user/invite"), UserPermission.INVITE_USERS);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/permissionDenied"), null).setVisible(false);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/utils/flushCache"), null).setVisible(false);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/login"), null).setVisible(false);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/loginError"), null).setVisible(false);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/logout"), null).setVisible(false);
......
......@@ -38,6 +38,7 @@ import fi.codecrew.moya.model.User;
UserPermission.S_MODIFY,
UserPermission.S_MODIFY_ACCOUNTEVENTS,
UserPermission.S_VIEW_ACCOUNTEVENTS,
UserPermission.S_VIEW_OWN_ACCOUNTEVENTS,
UserPermission.S_VIEW_ALL,
UserPermission.S_VIEW_SELF,
UserPermission.S_WRITE_ROLES,
......@@ -53,7 +54,7 @@ import fi.codecrew.moya.model.User;
MapPermission.S_MANAGE_MAPS,
MapPermission.S_MANAGE_OTHERS,
MapPermission.S_BUY_PLACES,
// MapPermission.S_RELEASE_PLACE,
// MapPermission.S_RELEASE_PLACE,
ShopPermission.S_LIST_ALL_PRODUCTS,
ShopPermission.S_LIST_USERPRODUCTS,
......@@ -165,7 +166,8 @@ public class PermissionBean implements PermissionBeanLocal {
}
/**
* Makes sure default user and public role exist and the user is member of the role.
* Makes sure default user and public role exist and the user is member of
* the role.
*/
@Override
public EventUser getAnonEventUser() {
......
......@@ -113,9 +113,12 @@ public class PlaceBean implements PlaceBeanLocal {
}
/**
* Calculate the price of reserved places for the user Optional parameter newPlace can be given when the place is added to the price calculations;
* Calculate the price of reserved places for the user Optional parameter
* newPlace can be given when the place is added to the price calculations;
*
* User parameter can be used to select another user than the currently logged in user, but if user does not have enough rights an exception will be thrown
* User parameter can be used to select another user than the currently
* logged in user, but if user does not have enough rights an exception will
* be thrown
*
*/
......@@ -182,7 +185,8 @@ public class PlaceBean implements PlaceBeanLocal {
}
/**
* Reserve the place for user. This reservation will timeout after a while buy() method should be called after this when buying place;
* Reserve the place for user. This reservation will timeout after a while
* buy() method should be called after this when buying place;
*
* @param place
* place to be reserved
......@@ -196,24 +200,33 @@ public class PlaceBean implements PlaceBeanLocal {
place = placeFacade.find(place.getId());
user = eventUserFacade.find(user.getId());
boolean ret = false;
if (place.isBuyable() && !place.isTaken()) {
place.setCurrentUser(user);
place.setReleaseTime(Calendar.getInstance());
place.getReleaseTime().add(Calendar.MINUTE, RESERVE_MINUTES);
// Create timeout service to timeout the reserved place in
// RESERVE_MINUTES
boolean foundTimeout = false;
for (Timer t : ts.getTimers()) {
if (t.getInfo().equals(PLACE_RESERVE_TIMEOUTER)) {
foundTimeout = true;
// when admin click's place, he reserves it -> just ignore it
if (!place.isTaken() || (permbean.hasPermission(MapPermission.MANAGE_OTHERS) && permbean.getCurrentUser().equals(place.getCurrentUser()))) {
if (place.isBuyable() || permbean.hasPermission(MapPermission.MANAGE_OTHERS)) {
if (!place.isBuyable()) {
place.setBuyable(true);
}
place.setCurrentUser(user);
place.setReleaseTime(Calendar.getInstance());
place.getReleaseTime().add(Calendar.MINUTE, RESERVE_MINUTES);
// Create timeout service to timeout the reserved place in
// RESERVE_MINUTES
boolean foundTimeout = false;
for (Timer t : ts.getTimers()) {
if (t.getInfo().equals(PLACE_RESERVE_TIMEOUTER)) {
foundTimeout = true;
}
}
if (!foundTimeout) {
logger.info("Place timeout calculator not started. Starting new.");
ts.createTimer(new Date(), 1000 * 60, PLACE_RESERVE_TIMEOUTER);
}
ret = true;
}
if (!foundTimeout) {
logger.info("Place timeout calculator not started. Starting new.");
ts.createTimer(new Date(), 1000 * 60, PLACE_RESERVE_TIMEOUTER);
}
ret = true;
}
return ret;
}
......@@ -237,10 +250,22 @@ public class PlaceBean implements PlaceBeanLocal {
// logger.debug("timeouting places");
// placeFacade.releasePlaces(permbean.getCurrentUser());
// }
@Override
@RolesAllowed({ MapPermission.S_BUY_PLACES, MapPermission.S_MANAGE_OTHERS })
public PlaceGroup buySelectedPlaces(EventUser user) throws BortalCatchableException {
return buyOrReserveSelectedPlaces(user, true);
}
@Override
@RolesAllowed({ MapPermission.S_MANAGE_OTHERS })
public PlaceGroup reserveSelectedPlaces(EventUser eventuser) throws BortalCatchableException {
return buyOrReserveSelectedPlaces(eventuser, false);
}
/**
* Reserves places and creates accountevents for the places.
*/
public PlaceGroup buyOrReserveSelectedPlaces(EventUser user, boolean createAccountevents) throws BortalCatchableException {
if (user == null) {
user = permbean.getCurrentUser();
} else {
......@@ -258,18 +283,19 @@ public class PlaceBean implements PlaceBeanLocal {
}
// PlaceGroup pg = pgbean.createPlaceGroup(user);
if (createAccountevents)
{
BigDecimal totalprice = addAndCalcPrice(user, null);
BigDecimal balance = user.getAccountBalance();
if (balance.compareTo(totalprice) < 0 && !permbean.hasPermission(MapPermission.MANAGE_OTHERS)) {
logger.info("User {} Could not buy things because account balance {} is too low for purchase {}", new Object[] { user, balance, totalprice });
return null;
}
BigDecimal totalprice = addAndCalcPrice(user, null);
BigDecimal balance = user.getAccountBalance();
if (balance.compareTo(totalprice) < 0 && !permbean.hasPermission(MapPermission.MANAGE_OTHERS)) {
logger.info("User {} Could not buy things because account balance {} is too low for purchase {}", new Object[] { user, balance, totalprice });
return null;
}
for (Entry<Product, Integer> line : getPlaceProductcount(places).entrySet()) {
productPBean.createAccountEvent(line.getKey(), new BigDecimal(line.getValue()), user, Calendar.getInstance());
for (Entry<Product, Integer> line : getPlaceProductcount(places).entrySet()) {
productPBean.createAccountEvent(line.getKey(), new BigDecimal(line.getValue()), user, Calendar.getInstance());
}
}
PlaceGroup pg = new PlaceGroup(event, Calendar.getInstance(), Calendar.getInstance(), true);
pg.setCreator(user);
pgfacade.create(pg);
......@@ -346,12 +372,17 @@ public class PlaceBean implements PlaceBeanLocal {
private static boolean isUserMember(EventUser user, Product prod) {
boolean ret = false;
for (GroupMembership gm : user.getGroupMemberships()) {
if (prod.equals(gm.getPlaceReservation().getProduct())) {
ret = true;
break;
if (user.getGroupMemberships() != null)
{
for (GroupMembership gm : user.getGroupMemberships()) {
if (gm.getPlaceReservation() != null && prod.equals(gm.getPlaceReservation().getProduct())) {
ret = true;
break;
}
}
}
return ret;
}
......@@ -527,7 +558,8 @@ public class PlaceBean implements PlaceBeanLocal {
PDF pdf = new PDF(outputStream);
pdf.setTitle("Place");
float pointInMillim = (25.4f / 72.0f); // 1 point is 1/72 inches. 1 inch = 25.4mm
float pointInMillim = (25.4f / 72.0f); // 1 point is 1/72 inches. 1 inch
// = 25.4mm
float pagex = width / pointInMillim;
float pagey = height / pointInMillim;
......@@ -546,7 +578,7 @@ public class PlaceBean implements PlaceBeanLocal {
double currentX = 42;
// nick
// nick
if (place.getPlaceReserver() != null && place.getPlaceReserver().getUser() != null) {
font = new com.pdfjet.Font(pdf, CoreFont.HELVETICA);
font.setSize(font2);
......@@ -558,12 +590,12 @@ public class PlaceBean implements PlaceBeanLocal {
textLine.drawOn(page);
}
// place hex code
// place hex code
font = new com.pdfjet.Font(pdf, CoreFont.HELVETICA);
font.setSize(font2);
textLine = new TextLine(font);
textLine.setText(barcodeBean.getPlaceHexcode(place));
textLine.setText(barcodeBean.getPlaceTextCode(place));
textLine.setPosition(currentX, (pagey / 2) + font1);
textLine.setColor(new int[] { 0, 0, 0 });
textLine.drawOn(page);
......@@ -586,4 +618,5 @@ public class PlaceBean implements PlaceBeanLocal {
throw new RuntimeException(e);
}
}
}
......@@ -34,20 +34,19 @@ import fi.codecrew.moya.model.LanEventPropertyKey;
import fi.codecrew.moya.model.PlaceGroup;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.utilities.BarcodeUtils;
import fi.codecrew.moya.utilities.I18n;
/**
* Session Bean implementation class PlaceGroupBean
*/
@Stateless
@DeclareRoles({ SpecialPermission.S_USER, MapPermission.S_BUY_PLACES })
@DeclareRoles({ SpecialPermission.S_USER, MapPermission.S_BUY_PLACES, MapPermission.S_MANAGE_MAPS })
public class PlaceGroupBean implements PlaceGroupBeanLocal {
private static final Logger logger = LoggerFactory.getLogger(PlaceGroupBean.class);
private static final int YSTART = 30;
@EJB
private EventBeanLocal eventbean;
@EJB
private BarcodeBeanLocal barcodeBean;
......@@ -87,7 +86,7 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
// }
@Override
@RolesAllowed(SpecialPermission.S_USER)
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public List<GroupMembership> getMembershipsAndCreations(EventUser user) {
if (user == null) {
user = permbean.getCurrentUser();
......@@ -99,7 +98,7 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public List<GroupMembership> getMemberships(EventUser user) {
if (user == null) {
user = permbean.getCurrentUser();
......@@ -133,59 +132,57 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public void getGroupMembershipPdf(EventUser usr, OutputStream ostream) {
List<GroupMembership> memberships = getMembershipsAndCreations(usr);
LanEventProperty tmpProperty = eventbean.getProperty(LanEventPropertyKey.PLACECODE_FROM_USER);
boolean placecodeFromUser = false;
if (tmpProperty != null && tmpProperty.isBooleanValue())
{
placecodeFromUser = true;
}
tmpProperty = eventbean.getProperty(LanEventPropertyKey.PLACECODE_PRINT_ONLY_OWN);
boolean printOnlyOwn = false;
if (tmpProperty != null && tmpProperty.isBooleanValue())
{
printOnlyOwn = true;
}
try {
PDF pdf = new PDF(ostream);
Font font = new Font(pdf, CoreFont.TIMES_ROMAN);
Font bigfont = new Font(pdf, CoreFont.TIMES_ROMAN);
bigfont.setSize(15);
Font titlefont = new Font(pdf, CoreFont.TIMES_ROMAN);
titlefont.setSize(20);
Page page = new Page(pdf, A4.PORTRAIT);
int y = YSTART;
String titletext = "Lipputositteet";
if(printOnlyOwn || memberships.size() <= 1) {
if (printOnlyOwn || memberships.size() <= 1) {
titletext = "Lipputosite";
}
TextLine topic = new TextLine(titlefont, titletext);
topic.setPosition(230, y);
topic.drawOn(page);
y += 30;
for (GroupMembership membership : memberships) {
if (y > 750) {
page = new Page(pdf, A4.PORTRAIT);
y = YSTART;
}
if(printOnlyOwn && (membership.getUser() == null || !membership.getUser().equals(usr))) {
if (printOnlyOwn && (membership.getUser() == null || !membership.getUser().equals(usr))) {
continue;
}
......@@ -194,16 +191,16 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
// PNGImage(BarcodeBean.getBarcode(membership.getInviteToken()));
// logger.debug("Jpeg: " + jpeg.getWidth() + " h. " +
// jpeg.getHeight());
if(placecodeFromUser) {
if(membership.getUser() != null) {
if (placecodeFromUser) {
if (membership.getUser() != null) {
Image image = new Image(pdf, barcodeBean.getUserBarcode(membership.getUser()), ImageType.PNG);
image.scaleBy(0.8);
image.setPosition(50, y);
image.drawOn(page);
} else {
TextLine nouser = new TextLine(bigfont, "EMPTY PLACE" );
nouser.setPosition(85, y+10);
TextLine nouser = new TextLine(bigfont, "EMPTY PLACE");
nouser.setPosition(85, y + 10);
nouser.drawOn(page);
}
} else {
......@@ -212,8 +209,6 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
image.setPosition(50, y);
image.drawOn(page);
}
StringBuilder sb = new StringBuilder();
if (membership.getPlaceReservation().getName() != null)
......@@ -246,24 +241,22 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
y += 130;
}
if (y > 750) {
page = new Page(pdf, A4.PORTRAIT);
y = YSTART;
}
String footertext = "Nämä lipputositteenne tulee olla tulostettuna paperille kun saavutte tapahtumaan.";
if(printOnlyOwn || memberships.size() <= 1) {
if (printOnlyOwn || memberships.size() <= 1) {
footertext = "Tämä henkilökohtainen lipputositteesi tulee olla mukana tulostettuna paperille kun saavut tapahtumaan.";
}
TextLine footer = new TextLine(font, footertext);
footer.setPosition(50, y);
footer.drawOn(page);
pdf.flush();
} catch (Exception e) {
logger.info("Error getting printing group memberships", e);
......@@ -272,19 +265,20 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public void releaseAndGenerateToken(GroupMembership gmem) {
gmem = gmemfacade.find(gmem.getId());
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");
}
gmem.setUser(null);
gmem.setInviteToken(gmemfacade.createInviteToken());
logger.info("Place released. {} new token {}", gmem.getInviteToken());
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public List<PlaceGroup> getPlacegroups(EventUser user) {
return pgfacade.find(user);
}
......@@ -299,6 +293,6 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
public void markGrouMembershipNotEntered(GroupMembership membership) {
membership.setEnteredEvent(null);
membership = gmemfacade.merge(membership);
}
}
......@@ -104,6 +104,9 @@ public class ProductBean implements ProductBeanLocal {
@EJB
private DiscountBean discountBean;
@EJB
private CardTemplateBean cardTemplateBean;
private static final Logger logger = LoggerFactory.getLogger(ProductBean.class);
/**
......@@ -350,6 +353,7 @@ public class ProductBean implements ProductBeanLocal {
public AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user) {
user = eventUserFacade.reload(user);
AccountEvent ret = productPBean.createAccountEvent(product, quantity, user, Calendar.getInstance());
cardTemplateBean.checkPrintedCard(user);
return ret;
}
......
......@@ -30,7 +30,7 @@ public class ProductPBean {
@EJB
private PermissionBean permbean;
@EJB
private DiscountBean discountBean;
@EJB
......@@ -100,10 +100,8 @@ public class ProductPBean {
// discountinstancefacade.create(discInst);
accEventdiscounts.add(new DiscountInstance(ret, d));
}
if (user.getAccountEvents() == null) {
user.setAccountEvents(new ArrayList<AccountEvent>());
}
user.getAccountEvents().add(ret);
user.addAccountevent(ret);
accounteventfacade.create(ret);
logger.debug("create ac {} for user {}", ret, user.getUser());
// flush changes to db.
......
package fi.codecrew.moya.beans;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.ejb.Singleton;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.facade.ApiApplicationFacade;
import fi.codecrew.moya.facade.ApiApplicationInstanceFacade;
import fi.codecrew.moya.utilities.PasswordFunctions;
/**
* Session Bean implementation class RestAuthBean
*/
@Singleton
@LocalBean
public class RestBean implements RestBeanLocal {
/**
* Default constructor.
*/
public RestBean() {
// TODO Auto-generated constructor stub
}
@Resource
private TimerService ts;
@Resource
private SessionContext context;
private static final Logger logger = LoggerFactory.getLogger(RestBean.class);
@PostConstruct
public void initialize() {
ts.createTimer(60 * 1000, 60 * 1000, null);
}
@EJB
private ApiApplicationFacade appfacade;
@EJB
private ApiApplicationInstanceFacade apiInstanceFacade;
@Timeout
public void timeoutNonces(Timer timer) {
int count = 0;
long now = System.currentTimeMillis();
synchronized (userRestAuths) {
for (Map<String, Long> ua : userRestAuths.values()) {
for (Entry<String, Long> no : ua.entrySet()) {
if (no != null && now > no.getValue()) {
ua.remove(no.getKey());
++count;
}
}
}
}
logger.info("Timeouted {} nonces", count);
}
// Username -> Nonce -> expiration
private Map<String, Map<String, Long>> userRestAuths = Collections.synchronizedMap(new HashMap<String, Map<String, Long>>());
@Override
public String getLoggedinUserRestNonce()
{
String username = context.getCallerPrincipal().getName();
if (username == null) {
return null;
}
Map<String, Long> userAuthMap = userRestAuths.get(username);
if (userAuthMap == null) {
synchronized (userRestAuths) {
if (!userRestAuths.containsKey(username)) {
userAuthMap = Collections.synchronizedMap(new HashMap<String, Long>());
userRestAuths.put(username, userAuthMap);
}
}
}
Random random = new Random();
int charcount = 20 + random.nextInt(10);
String nonce = null;
do {
nonce = PasswordFunctions.generateRandomString(charcount, PasswordFunctions.ALL_CHARS);
} while (userAuthMap.containsKey(nonce));
userAuthMap.put(nonce, System.currentTimeMillis() + 120 * 1000); // Timeout in 60 seconds.
return nonce;
}
@Override
public boolean validateUserNonce(String nonce) {
String username = context.getCallerPrincipal().getName();
boolean ret = false;
// Validation is successfull if user exists, nonce exists and timeout has not passed.
if (username != null && userRestAuths.containsKey(username)) {
Long time = userRestAuths.get(username).remove(nonce);
ret = time != null && time > System.currentTimeMillis();
}
return ret;
}
}
......@@ -21,6 +21,7 @@ import org.slf4j.LoggerFactory;
import fi.codecrew.moya.enums.apps.IAppPermission;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.facade.RoleFacade;
import fi.codecrew.moya.facade.UserFacade;
import fi.codecrew.moya.model.ApplicationPermission;
......@@ -51,6 +52,15 @@ public class RoleBean implements RoleBeanLocal {
@EJB
private UserFacade userFacade;
@EJB
private EventUserFacade eventuserfacade;
@EJB
private EventBeanLocal permbean;
@EJB
private CardTemplateBean cardTemplateBean;
// VIEW_ALL pitää olla että voidaan hakea roolien perusteella.
@Override
@RolesAllowed({ UserPermission.S_READ_ROLES, UserPermission.S_VIEW_ALL })
......@@ -161,6 +171,28 @@ public class RoleBean implements RoleBeanLocal {
return role;
}
private void checkRoleLdap()
{
}
@Override
@RolesAllowed(UserPermission.S_WRITE_ROLES)
public Role addRole(EventUser eventuser, Role role)
{
eventuser = eventuserfacade.reload(eventuser);
role = roleFacade.reload(role);
if (!eventuser.getRoles().contains(role)) {
eventuser.getRoles().add(role);
}
if (!role.getUsers().contains(eventuser)) {
role.getUsers().add(eventuser);
}
cardTemplateBean.checkPrintedCard(eventuser);
return role;
}
@Override
@RolesAllowed(UserPermission.S_WRITE_ROLES)
public void saveRoles(EventUser usr, List<Role> usersRoles) {
......@@ -176,6 +208,8 @@ public class RoleBean implements RoleBeanLocal {
ur.getUsers().remove(usr);
}
}
cardTemplateBean.checkPrintedCard(usr);
}
@Override
......
......@@ -59,6 +59,7 @@ public class VotingBean implements VotingBeanLocal {
voteFacade.create(v);
}
@RolesAllowed(CompoPermission.S_MANAGE)
public void createCompo(Compo c) {
c.setEvent(eventBean.getCurrentEvent());
compoFacade.create(c);
......@@ -73,15 +74,15 @@ public class VotingBean implements VotingBeanLocal {
c.getCompoEntries().add(compoEntry);
compoFacade.flush();
compoEntryFile.setEntriesId(compoEntry);
compoEntry.getFiles().add(compoEntryFile);
// compoEntry.getFiles().add(compoEntryFile);
}
public Compo getCompoById(Integer compoId) {
return compoFacade.find(compoId);
}
public List<Compo> getCompoList() {
return compoFacade.getList();
public List<Compo> getCompoList(boolean showHidden) {
return compoFacade.getList(showHidden);
}
@Override
......@@ -129,16 +130,17 @@ public class VotingBean implements VotingBeanLocal {
return compoEntryFacade.find(entryId);
}
@Override
public CompoEntry findEntryWithFiles(Integer entryId) {
CompoEntry ret = compoEntryFacade.find(entryId);
logger.debug("Found files {}", ret.getFiles().size());
return ret;
}
// @Override
// public CompoEntry findEntryWithFiles(Integer entryId) {
// CompoEntry ret = compoEntryFacade.find(entryId);
// // logger.debug("Found files {}", ret.getFiles().size());
//
// return ret;
//
// }
@Override
@RolesAllowed(CompoPermission.S_MANAGE)
public CompoEntry saveSort(CompoEntry e) {
CompoEntry entry = compoEntryFacade.find(e.getId());
entry.setSort(e.getSort());
......@@ -177,4 +179,15 @@ public class VotingBean implements VotingBeanLocal {
return voteEntity;
}
@Override
@RolesAllowed(CompoPermission.S_MANAGE)
public Compo saveCompo(Compo compo) {
return compoFacade.merge(compo);
}
@Override
public void create(CompoEntryFile cef) {
compoEntryFileFacade.create(cef);
}
}
package fi.codecrew.moya.facade;
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.ApiApplication;
import fi.codecrew.moya.model.ApiApplication_;
@Stateless
@LocalBean
public class ApiApplicationFacade extends IntegerPkGenericFacade<ApiApplication> {
public ApiApplicationFacade() {
super(ApiApplication.class);
}
public ApiApplication findByAppid(String appId) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<ApiApplication> q = cb.createQuery(ApiApplication.class);
Root<ApiApplication> root = q.from(ApiApplication.class);
q.where(cb.equal(root.get(ApiApplication_.applicationKey), appId));
return super.getSingleNullableResult(getEm().createQuery(q));
}
}
package fi.codecrew.moya.facade;
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.ApiApplication;
import fi.codecrew.moya.model.ApiApplicationInstance;
import fi.codecrew.moya.model.ApiApplicationInstance_;
@Stateless
@LocalBean
public class ApiApplicationInstanceFacade extends IntegerPkGenericFacade<ApiApplicationInstance> {
public ApiApplicationInstanceFacade() {
super(ApiApplicationInstance.class);
}
public ApiApplicationInstance findInstance(ApiApplication app, String userId) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<ApiApplicationInstance> q = cb.createQuery(ApiApplicationInstance.class);
Root<ApiApplicationInstance> root = q.from(ApiApplicationInstance.class);
q.where(cb.equal(root.get(ApiApplicationInstance_.application), app),
cb.equal(root.get(ApiApplicationInstance_.authname), userId));
return super.getSingleNullableResult(getEm().createQuery(q));
}
}
......@@ -3,14 +3,14 @@ package fi.codecrew.moya.facade;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import fi.codecrew.moya.model.CardBarcode;
import fi.codecrew.moya.model.CardCode;
@Stateless
@LocalBean
public class CardBarcodeFacade extends IntegerPkGenericFacade<CardBarcode> {
public class CardCodeFacade extends IntegerPkGenericFacade<CardCode> {
public CardBarcodeFacade() {
super(CardBarcode.class);
public CardCodeFacade() {
super(CardCode.class);
}
}
package fi.codecrew.moya.facade;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
......@@ -7,11 +8,12 @@ import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.Compo_;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.Compo;
import fi.codecrew.moya.model.Compo_;
@Stateless
@LocalBean
......@@ -23,11 +25,17 @@ public class CompoFacade extends IntegerPkGenericFacade<Compo> {
super(Compo.class);
}
public List<Compo> getList() {
public List<Compo> getList(boolean showHidden) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<Compo> cq = cb.createQuery(Compo.class);
Root<Compo> root = cq.from(Compo.class);
cq.where(cb.equal(root.get(Compo_.event), eventbean.getCurrentEvent()));
ArrayList<Predicate> preds = new ArrayList<>();
preds.add(cb.equal(root.get(Compo_.event), eventbean.getCurrentEvent()));
if (!showHidden) {
preds.add(cb.isFalse(root.get(Compo_.hidden)));
}
cq.where(preds.toArray(new Predicate[preds.size()]));
cq.orderBy(cb.desc(root.get(Compo_.startTime)));
List<Compo> ret = getEm().createQuery(cq).getResultList();
return ret;
......
......@@ -13,15 +13,21 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.enums.DatabaseHasCompare;
import fi.codecrew.moya.enums.DatabaseValueCompare;
import fi.codecrew.moya.facade.callbacks.EventLimiter;
import fi.codecrew.moya.facade.callbacks.EventUserAccountSaldoPredicate;
import fi.codecrew.moya.facade.callbacks.EventUserCardStateFilter;
import fi.codecrew.moya.facade.callbacks.EventUserPlacegroupPredicate;
import fi.codecrew.moya.facade.callbacks.EventUserRolefilter;
import fi.codecrew.moya.facade.callbacks.EventUserSearchPredicate;
import fi.codecrew.moya.facade.callbacks.EventuserToUserWrapper;
import fi.codecrew.moya.facade.callbacks.OrderCallback;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
......@@ -29,6 +35,7 @@ import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.User_;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
......@@ -47,6 +54,7 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
}
private final Map<Integer, Map<String, Integer>> logincache = new HashMap<Integer, Map<String, Integer>>();
private static final Logger logger = LoggerFactory.getLogger(EventUserFacade.class);
public EventUser findByLogin(final String login) {
LanEvent event = eventBean.getCurrentEvent();
......@@ -82,10 +90,13 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
}
public EventUser find(User user) {
LanEvent event = eventBean.getCurrentEvent();
EventUser ret;
if ((ret = checkCache(user.getLogin(), event)) == null)
{
return getOtherOrganisationsEventuser(user, eventBean.getCurrentEvent());
}
public EventUser getOtherOrganisationsEventuser(User user, LanEvent event)
{
EventUser ret = null;
if ((ret = checkCache(user.getLogin(), event)) == null) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<EventUser> cq = cb.createQuery(EventUser.class);
Root<EventUser> root = cq.from(EventUser.class);
......@@ -108,19 +119,40 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
public SearchResult<EventUser> searchEventUsers(UserSearchQuery query) {
ArrayList<FacadeCallback<EventUser>> callbacks = new ArrayList<FacadeCallback<EventUser>>();
callbacks.add(new OrderCallback<EventUser>(false, EventUser_.id));
callbacks.add(new EventLimiter(eventBean.getCurrentEvent()));
if (query.getSearch() != null && !query.getSearch().isEmpty())
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<EventUser> listCQuery = cb.createQuery(EventUser.class);
CriteriaQuery<Long> countCQuery = cb.createQuery(Long.class);
if (query.getSort() != null)
{
boolean asc = false;
if (query.getSortDirection() != null) {
asc = QuerySortOrder.ASCENDING.equals(query.getSortDirection());
}
SingularAttribute<? super User, ?> sortfield = UserFacade.getUserField(query.getSort());
logger.info("Sortig with {}, asc {} ", sortfield, asc);
callbacks.add(new EventuserToUserWrapper(new OrderCallback<User>(asc, sortfield)));
} else {
callbacks.add(new OrderCallback<EventUser>(false, EventUser_.id));
}
callbacks.add(new EventLimiter(eventBean.getCurrentEvent()));
if (query.getSearch() != null && !query.getSearch().isEmpty()) {
callbacks.add(new EventUserSearchPredicate(query.getSearch(), UserFacade.getAttrlist()));
}
if (query.isPlaceAssoc())
{
if (query.isPlaceAssoc()) {
callbacks.add(new EventUserPlacegroupPredicate());
}
if (query.getFilterRoles() != null && !query.getFilterRoles().isEmpty()) {
callbacks.add(new EventUserRolefilter(query.getFilterRoles()));
}
if (query.getHasCardState() != null && !query.getHasCardState().isEmpty()) {
callbacks.add(new EventUserCardStateFilter(query.getHasCardState()));
}
if (query.getAccountSaldo() != null &&
query.getAccountSaldoCompare() != null &&
!DatabaseValueCompare.NONE.equals(query.getAccountSaldoCompare()))
......@@ -132,11 +164,6 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
}
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<EventUser> listCQuery = cb.createQuery(EventUser.class);
CriteriaQuery<Long> countCQuery = cb.createQuery(Long.class);
From<?, EventUser> listRoot = searchCallbacks(listCQuery, callbacks, EventUser.class);
From<?, EventUser> countRoot = searchCallbacks(countCQuery, callbacks, EventUser.class);
......
......@@ -9,10 +9,10 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.OrgRole_;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.EventOrganiser;
import fi.codecrew.moya.model.OrgRole;
import fi.codecrew.moya.model.OrgRole_;
import fi.codecrew.moya.model.User;
/**
......@@ -29,17 +29,19 @@ public class OrgRoleFacade extends IntegerPkGenericFacade<OrgRole> {
super(OrgRole.class);
}
public List<OrgRole> findForUser(User user) {
public List<OrgRole> findForUser(User user, EventOrganiser organisation) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<OrgRole> cq = cb.createQuery(OrgRole.class);
Root<OrgRole> root = cq.from(OrgRole.class);
cq.where(cb.equal(root.get(OrgRole_.eventOrganisation), eventBean
.getCurrentEvent().getOrganiser()), cb.isMember(user,
root.get(OrgRole_.users)));
cq.where(cb.equal(root.get(OrgRole_.eventOrganisation), organisation), cb.isMember(user, root.get(OrgRole_.users)));
return getEm().createQuery(cq).getResultList();
}
public List<OrgRole> findForUser(User user) {
return findForUser(user, eventBean.getCurrentEvent().getOrganiser());
}
public OrgRole createRole(EventOrganiser org, String roleName) {
OrgRole ret = new OrgRole();
ret.setEventOrganisation(org);
......
......@@ -3,7 +3,6 @@ package fi.codecrew.moya.facade;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import javax.ejb.EJB;
......@@ -14,9 +13,12 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.model.CardCode;
import fi.codecrew.moya.model.CardCode_;
import fi.codecrew.moya.model.CardTemplate_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEvent;
......@@ -35,31 +37,19 @@ public class PrintedCardFacade extends IntegerPkGenericFacade<PrintedCard> {
@EJB
private EventBeanLocal eventbean;
public PrintedCard findByRfid(String uid) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<PrintedCard> cq = cb.createQuery(PrintedCard.class);
Root<PrintedCard> root = cq.from(PrintedCard.class);
cq.where(
cb.or(
cb.equal(root.get(PrintedCard_.barcode), uid),
cb.equal(root.get(PrintedCard_.rfidUid), uid)),
cb.equal(root.get(PrintedCard_.event), eventbean.getCurrentEvent()));
return getSingleNullableResult(getEm().createQuery(cq));
}
public PrintedCard findByBarcode(String barcode) {
public PrintedCard findByCode(String code) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<PrintedCard> cq = cb.createQuery(PrintedCard.class);
Root<PrintedCard> root = cq.from(PrintedCard.class);
CriteriaQuery<CardCode> cq = cb.createQuery(CardCode.class);
Root<CardCode> root = cq.from(CardCode.class);
cq.where(cb.equal(root.get(PrintedCard_.barcode), barcode),
cb.equal(root.get(PrintedCard_.event), eventbean.getCurrentEvent()));
cq.where(cb.equal(root.get(CardCode_.code), code),
cb.equal(root.get(CardCode_.event), eventbean.getCurrentEvent()));
return getSingleNullableResult(getEm().createQuery(cq));
CardCode cardcode = getSingleNullableResult(getEm().createQuery(cq));
return (cardcode == null)?null : cardcode.getPrintedCard();
}
public List<PrintedCard> findAllEnabled(LanEvent currentEvent) {
......@@ -85,14 +75,16 @@ public class PrintedCardFacade extends IntegerPkGenericFacade<PrintedCard> {
}
public PrintedCard findLatestByRfidFromAny(String uid) {
public PrintedCard findLatestByCodeFromAny(String code) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<PrintedCard> cq = cb.createQuery(PrintedCard.class);
Root<PrintedCard> root = cq.from(PrintedCard.class);
cq.where(cb.equal(root.get(PrintedCard_.rfidUid), uid));
cq.orderBy(cb.desc(root.get(PrintedCard_.printTime)));
Root<CardCode> root = cq.from(CardCode.class);
cq.select(root.get(CardCode_.printedCard));
cq.where(cb.equal(root.get(CardCode_.code), code));
cq.orderBy(cb.desc(root.get(CardCode_.printedCard).get(PrintedCard_.printTime)));
TypedQuery<PrintedCard> q = getEm().createQuery(cq);
q.setMaxResults(1);
......
......@@ -11,10 +11,11 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.Product_;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.Product;
import fi.codecrew.moya.model.ProductFlag;
import fi.codecrew.moya.model.Product_;
@Stateless
@LocalBean
......@@ -44,11 +45,15 @@ public class ProductFacade extends IntegerPkGenericFacade<Product> {
}
public List<Product> findProductsByPrice(BigDecimal price) {
return findProductsByPrice(price, eventbean.getCurrentEvent());
}
public List<Product> findProductsByPrice(BigDecimal price, LanEvent event) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> root = cq.from(Product.class);
cq.where(cb.equal(root.get(Product_.event), eventbean.getCurrentEvent()),
cq.where(cb.equal(root.get(Product_.event), event),
cb.equal(root.get(Product_.price), price));
return getEm().createQuery(cq).getResultList();
......@@ -65,18 +70,19 @@ public class ProductFacade extends IntegerPkGenericFacade<Product> {
return getEm().createQuery(cq).getResultList();
}
public Product findProductByBarcode(String barcode) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> root = cq.from(Product.class);
cq.where(
cq.where(
cb.equal(root.get(Product_.event), eventbean.getCurrentEvent()),
cb.equal(root.get(Product_.barcode), barcode)
);
return super.getSingleNullableResult(getEm().createQuery(cq));
}
}
......@@ -31,8 +31,26 @@ public class ReaderEventFacade extends IntegerPkGenericFacade<ReaderEvent> {
cq.orderBy(cb.desc(root.get(ReaderEvent_.time)));
TypedQuery<ReaderEvent> q = getEm().createQuery(cq);
q.setMaxResults(count);
if (count > 0) {
q.setMaxResults(count);
}
return q.getResultList();
}
public List<ReaderEvent> findEventsAfterEvent(Reader reader, Integer eventId) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<ReaderEvent> cq = cb.createQuery(ReaderEvent.class);
Root<ReaderEvent> root = cq.from(ReaderEvent.class);
cq.where(cb.equal(root.get(ReaderEvent_.reader), reader),
cb.gt(root.get(ReaderEvent_.id), eventId));
cq.orderBy(cb.desc(root.get(ReaderEvent_.time)));
TypedQuery<ReaderEvent> q = getEm().createQuery(cq);
return q.getResultList();
}
}
......@@ -15,12 +15,13 @@ import javax.persistence.metamodel.SingularAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.facade.callbacks.OrderCallback;
import fi.codecrew.moya.facade.callbacks.StringSearchPredicateCreator;
import fi.codecrew.moya.model.User_;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.User_;
import fi.codecrew.moya.utilities.SearchQuery;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
......@@ -102,11 +103,11 @@ public class UserFacade extends IntegerPkGenericFacade<User> {
public SearchResult<User> searchAllUsers(SearchQuery search) {
List<FacadeCallback<User>> callbacks = new ArrayList<FacadeCallback<User>>();
if (search.getSort() == null || search.getSort().isEmpty()) {
callbacks.add(new OrderCallback<User>(false, User_.id));
} else {
callbacks.add(new OrderCallback<User>(false, search.getSort()));
}
// Ascending if null or not descending..
boolean asc = search.getSortDirection() == null || !QuerySortOrder.DESCENDING.equals(search.getSortDirection());
SingularAttribute<? super User, ?> sortfield = getUserField(search.getSort());
callbacks.add(new OrderCallback<User>(asc, sortfield));
callbacks.add(new StringSearchPredicateCreator<User>(search.getSearch(), getAttrlist()));
return super.searcher(search, callbacks);
......@@ -142,6 +143,68 @@ public class UserFacade extends IntegerPkGenericFacade<User> {
return getEm().createQuery(cq).getResultList();
}
/**
* For example in sorting.
*
* @param fieldname
* @return By default return "id"
*/
public static SingularAttribute<? super User, ?> getUserField(String fieldname) {
SingularAttribute<? super User, ?> sort = User_.id;
if (fieldname != null)
{
switch (fieldname) {
case "created":
sort = User_.created;
break;
case "login":
sort = User_.login;
break;
case "lastname":
sort = User_.lastname;
break;
case "firstnames":
sort = User_.firstnames;
break;
case "birthday":
sort = User_.birthday;
break;
case "nick":
sort = User_.nick;
break;
case "email":
sort = User_.email;
break;
case "address":
sort = User_.address;
break;
case "zip":
sort = User_.zip;
break;
case "postalTown":
sort = User_.postalTown;
break;
case "town":
sort = User_.town;
break;
case "phone":
sort = User_.phone;
break;
case "gender":
sort = User_.gender;
break;
case "confirmTime":
sort = User_.confirmTime;
break;
case "id":
default:
sort = User_.id;
}
}
return sort;
}
// public SearchResult<User> searchEventUsers(SearchQuery query)
// {
// ArrayList<FacadeCallback<EventUser>> callbacks = new
......
......@@ -5,7 +5,7 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
......@@ -27,7 +27,7 @@ public class AndPredicateCreator<A, T extends ModelInterface> implements FacadeC
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, T> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates) {
if (searchval == null || attributes == null || attributes.isEmpty()) {
return;
}
......
......@@ -4,11 +4,11 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
......@@ -21,7 +21,7 @@ public class EventLimiter implements FacadeCallback<EventUser> {
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, EventUser> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
predicates.add(cb.equal(root.get(EventUser_.event), ev));
}
......
......@@ -5,14 +5,14 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import fi.codecrew.moya.model.AccountEvent_;
import fi.codecrew.moya.enums.DatabaseValueCompare;
import fi.codecrew.moya.model.AccountEvent;
import fi.codecrew.moya.model.AccountEvent_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
......@@ -27,7 +27,7 @@ public class EventUserAccountSaldoPredicate implements FacadeCallback<EventUser>
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, EventUser> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
Subquery<BigDecimal> subq = cq.subquery(BigDecimal.class);
Root<AccountEvent> acRoot = subq.from(AccountEvent.class);
subq.where(cb.equal(acRoot.get(AccountEvent_.user), root));
......
package fi.codecrew.moya.facade.callbacks;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.PrintedCard;
import fi.codecrew.moya.model.PrintedCard_;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventUserCardStateFilter implements FacadeCallback<EventUser> {
private final List<CardState> states;
private static final Logger logger = LoggerFactory.getLogger(EventUserCardStateFilter.class);
public EventUserCardStateFilter(List<CardState> statelist) {
this.states = statelist;
}
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
if (states != null && !states.isEmpty())
{
for (CardState s : states)
{
logger.info("Statte {}, type {}", s, s.getClass());
}
logger.debug("Requiring states {}", states);
Path<Integer> rootId = root.get(EventUser_.id);
Subquery<Integer> subq = cq.subquery(Integer.class);
Root<PrintedCard> subroot = subq.from(PrintedCard.class);
subq.select(subroot.join(PrintedCard_.user).get(EventUser_.id));
subq.where(subroot.get(PrintedCard_.cardState).in(states));
predicates.add(rootId.in(subq));
}
}
}
......@@ -4,17 +4,17 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventUserPlacegroupPredicate implements FacadeCallback<EventUser> {
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, EventUser> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
predicates.add(cb.isNotEmpty(root.get(EventUser_.groupMemberships)));
}
......
......@@ -8,7 +8,6 @@ import java.util.Set;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
......@@ -18,13 +17,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.model.AccountEvent_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.GroupMembership_;
import fi.codecrew.moya.model.Place_;
import fi.codecrew.moya.model.Product_;
import fi.codecrew.moya.model.Role_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.model.Role_;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventUserRolefilter implements FacadeCallback<EventUser> {
......@@ -49,7 +48,7 @@ public class EventUserRolefilter implements FacadeCallback<EventUser> {
return checkedRoles;
}
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, EventUser> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
if (roles != null && !roles.isEmpty())
{
HashSet<Integer> roleids = new HashSet<Integer>();
......
package fi.codecrew.moya.facade.callbacks;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventuserToUserWrapper implements FacadeCallback<EventUser> {
private final FacadeCallback<User>[] callbacks;
@SafeVarargs
public EventuserToUserWrapper(FacadeCallback<User>... wrapped)
{
this.callbacks = wrapped;
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
for (FacadeCallback<User> subcallback : callbacks) {
subcallback.exec(cb, cq, root.get(EventUser_.user), predicates);
}
}
}
......@@ -4,7 +4,7 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
......@@ -25,7 +25,7 @@ public class OrPredicateCreator<A, T extends ModelInterface> implements FacadeCa
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, T> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates) {
if (searchstr == null || attributes == null || attributes.isEmpty()) {
return;
}
......
......@@ -4,11 +4,14 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
import fi.codecrew.moya.utilities.jpa.ModelInterface;
......@@ -17,6 +20,7 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T
private final SingularAttribute<? super T, ?> sort;
private final boolean asc;
private String sortstr;
private static final Logger logger = LoggerFactory.getLogger(OrderCallback.class);
public OrderCallback(boolean asc, SingularAttribute<? super T, ?> sortAttr) {
sort = sortAttr;
......@@ -31,16 +35,15 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, T> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates) {
Class<?> rettype = cq.getResultType();
// Check if returntype is entity or are we for example counting results
if (!ModelInterface.class.isAssignableFrom(rettype))
{
if (!ModelInterface.class.isAssignableFrom(rettype)) {
return;
}
Path<?> path = null;
Expression<?> path = null;
if (sort == null) {
if (sortstr == null) {
return;
......@@ -56,6 +59,9 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T
if (path == null) {
return;
}
if (path.getJavaType().equals(String.class)) {
path = cb.lower((Expression<String>) path);
}
if (asc) {
cq.orderBy(cb.asc(path));
......
......@@ -5,7 +5,6 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
......@@ -44,7 +43,7 @@ public abstract class PathStringSearchPredicateCreator<T extends ModelInterface,
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, T> path, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> path, List<Predicate> predicates) {
if (searchstr == null || attributes == null || attributes.isEmpty()) {
return;
}
......
......@@ -62,5 +62,11 @@
<artifactId>httpclient</artifactId>
<version>4.3-beta2</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.5</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package fi.codecrew.moya.beans;
import org.testng.annotations.Test;
public class BarcodeTests {
@Test
public void tbd() {
}
}
......@@ -8,6 +8,7 @@ import javax.ejb.Local;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Place;
import fi.codecrew.moya.model.PrintedCard;
import fi.codecrew.moya.model.Product;
@Local
public interface BarcodeBeanLocal {
......@@ -17,8 +18,11 @@ public interface BarcodeBeanLocal {
public InputStream getUserBarcode(EventUser user) throws IOException;
public InputStream getCardBarcode(PrintedCard printedCard) throws IOException;
public String getPlaceHexcode(Place place);
public Place getPlaceFromHexcode(String hexcode);
public String getPlaceTextCode(Place place);
public Place getPlaceFromTextCode(String hexcode);
public String checkVrAuthCode(String code);
public Product getProduct(String barcode);
public Place getPlaceFromBarcode(String barcode);
}
......@@ -9,6 +9,7 @@ import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.model.CardTemplate;
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
......
......@@ -35,7 +35,13 @@ public interface EventBeanLocal {
List<LanEventPrivateProperty> getPrivateProperties();
LanEventPrivateProperty saveOrCreatePrivateProperty(LanEventPrivateProperty privateProperty);
long getPropertyLong(LanEventPropertyKey property);
LanEvent getEventById(Integer id);
LanEvent deleteProperty(LanEventProperty property);
LanEvent deletePrivateProperty(LanEventPrivateProperty property);
}
......@@ -24,4 +24,6 @@ public interface EventMapBeanLocal {
Place updatePlace(Place place);
void createPlace(Place create);
}
package fi.codecrew.moya.beans;
import javax.ejb.Local;
@Local
public interface LdapBeanLocal {
}
......@@ -63,10 +63,13 @@ public interface PlaceBeanLocal {
*/
byte[] generatePlacesPdf(float width, float height, double font1, double font2);
// public byte[] generatePlacesPdf(double width, double height, double font1, double font2);
List<GroupMembership> matchGroupMembershipsByInviteToken(String token);
GroupMembership findGroupMembershipsByToken(String token);
PlaceGroup reserveSelectedPlaces(EventUser eventuser) throws BortalCatchableException;
}
......@@ -17,7 +17,7 @@ public interface ReaderBeanLocal {
// ReaderEvent assocTagToPlacecode(String tag, String readerIdent, String
// placecode) throws BortalCatchableException, PermissionDeniedException;
ReaderEvent assocTagToCard(String tag, String readerIdent, PrintedCard card);
ReaderEvent assocCodeToCard(ReaderEvent readerEvent, PrintedCard card);
List<Reader> getReaders();
......@@ -27,7 +27,8 @@ public interface ReaderBeanLocal {
User findTagFromAnyEvent(String value);
ReaderEvent createCard(ReaderEvent event, EventUser user);
// lets comment this out, so I can see where this is going
// ReaderEvent createCard(ReaderEvent event, EventUser user);
Reader getReader(Integer readerid);
......@@ -39,6 +40,12 @@ public interface ReaderBeanLocal {
List<ReaderEvent> getLastReaderEvents();
ReaderEvent checkTag(String readerIdent, String tag);
ReaderEvent checkCode(String readerIdent, String code);
ReaderEvent checkCode(Reader reader, String code);
List<ReaderEvent> getReaderEvents(Integer readerId, Integer count);
List<ReaderEvent> getReaderEventsAfterEvent(Integer readerId, Integer eventId);
}
package fi.codecrew.moya.beans;
import javax.ejb.Local;
@Local
public interface RestBeanLocal {
boolean validateUserNonce(String nonce);
String getLoggedinUserRestNonce();
// String authenticateApp(String pathInfo, String appId, String userid, String applicationStamp, String mac);
}
......@@ -36,4 +36,6 @@ public interface RoleBeanLocal {
public List<Role> getRoles(EventUser selectedUser);
Role addRole(EventUser eventuser, Role role);
}
......@@ -2,6 +2,7 @@ package fi.codecrew.moya.beans;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import javax.ejb.Local;
......@@ -10,6 +11,7 @@ import fi.codecrew.moya.model.EventUser;
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.Role;
import fi.codecrew.moya.model.TournamentGame;
import fi.codecrew.moya.model.User;
......@@ -26,7 +28,7 @@ public interface UserBeanLocal {
SearchResult<User> getUsers(SearchQuery search);
SearchResult<User> getEventUsers(SearchQuery search);
//SearchResult<User> getEventUsers(SearchQuery search);
EventUser mergeChanges(EventUser user);
......@@ -40,6 +42,8 @@ public interface UserBeanLocal {
boolean resetPassword(User user, String password, String hash);
public User getUser(Integer id);
/**
* Search EventUser entity by User entity ID
*
......@@ -47,13 +51,15 @@ public interface UserBeanLocal {
* ID of the User entity to be searcher
* @return
*/
EventUser findByUserId(Integer userid);
EventUser findByUserId(Integer userid, boolean createEventuser);
EventUser findByEventUserId(Integer integer);
GroupMembership findToken(String token);
void createFromToken(EventUser user, String token);
boolean createFromInviteToken(EventUser user, String token);
EventUser acceptInviteForExistingUser(String username, String password, String token);
UserImage findUserimageFORCE(Integer id);
......@@ -70,12 +76,13 @@ public interface UserBeanLocal {
List<Role> findUsersRoles(EventUser u);
/**
* NOTICE! If the user parameter is a persisted object the returned EventUser has a reloaded user, eg changes to the User object are lost!
* NOTICE! If the user parameter is a persisted object the returned
* EventUser has a reloaded user, eg changes to the User object are lost!
*
* @param user
* @return
*/
EventUser getEventUser(User user);
EventUser getEventUser(User user, boolean create);
EventUser validateUser(String username, String password);
......@@ -101,4 +108,23 @@ public interface UserBeanLocal {
boolean isUserInRole(EventUser user, Integer roleId);
EventUser getOtherEventsEventuser(User user, LanEvent event);
/**
* Transfers account saldo from previous event. Creates negative
* accountevent for source user and positive for dst user. There are few
* requirements.
* <ul>
* <li>User must be the same.
* <li>Organisation must be the same.
* <li>All users should have positive or zero balance on source event.
* </ul>
*
* @param source
* @param dst
* @return Saldo transferred. Zero if no transfer was made, Null if there
* was error..
*/
BigDecimal transferAccountSaldoFromPreviousEvent(List<User> dstEventuser, LanEvent source);
}
......@@ -15,7 +15,7 @@ public interface VotingBeanLocal {
public void addEntry(CompoEntry compoEntry, CompoEntryFile compoEntryFile);
public List<Compo> getCompoList();
public List<Compo> getCompoList(boolean showHidden);
public Compo getCompoById(Integer compoId);
......@@ -33,6 +33,10 @@ public interface VotingBeanLocal {
public Vote saveVote(CompoEntry entry, Integer vote);
public CompoEntry findEntryWithFiles(Integer entryId);
//public CompoEntry findEntryWithFiles(Integer entryId);
public Compo saveCompo(Compo compo);
public void create(CompoEntryFile cef);
}
......@@ -4,6 +4,7 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.enums.DatabaseHasCompare;
import fi.codecrew.moya.enums.DatabaseValueCompare;
import fi.codecrew.moya.model.Role;
......@@ -18,10 +19,24 @@ public class UserSearchQuery extends SearchQuery {
private boolean placeAssoc = false;
private boolean usersWithUnusedCodes = false;
private DatabaseHasCompare requireImage = DatabaseHasCompare.NONE;
private List<CardState> hasCardState = new ArrayList<>();
private BigDecimal accountSaldo;
private DatabaseValueCompare accountSaldoCompare = DatabaseValueCompare.NONE;
public UserSearchQuery() {
super();
}
public CardState[] getCardStates()
{
return CardState.values();
}
public UserSearchQuery(int page, int pagesize, String sort, String search, QuerySortOrder direction) {
super(page, pagesize, sort, search, direction);
}
public DatabaseValueCompare[] getAccountCompareValues()
{
return DatabaseValueCompare.values();
......@@ -38,11 +53,11 @@ public class UserSearchQuery extends SearchQuery {
public boolean isUsersWithUnusedCodes() {
return usersWithUnusedCodes;
}
public void setUsersWithUnusedCodes(boolean usersWithUnusedCodes) {
this.usersWithUnusedCodes = usersWithUnusedCodes;
}
public List<Role> getFilterRoles() {
return filterRoles;
}
......@@ -83,4 +98,12 @@ public class UserSearchQuery extends SearchQuery {
this.requireImage = requireImage;
}
public List<CardState> getHasCardState() {
return hasCardState;
}
public void setHasCardState(List<CardState> hasCardState) {
this.hasCardState = hasCardState;
}
}
......@@ -15,7 +15,7 @@ org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=1
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
org.eclipse.jdt.core.formatter.alignment_for_assignment=0
org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
......@@ -90,7 +90,7 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false
org.eclipse.jdt.core.formatter.indentation.size=8
org.eclipse.jdt.core.formatter.indentation.size=4
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert
......@@ -283,7 +283,7 @@ org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
org.eclipse.jdt.core.formatter.tabulation.char=space
org.eclipse.jdt.core.formatter.tabulation.char=tab
org.eclipse.jdt.core.formatter.tabulation.size=4
org.eclipse.jdt.core.formatter.use_on_off_tags=false
org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
......
cleanup_settings_version=2
eclipse.preferences.version=1
formatter_profile=_InsomniaConventions
formatter_profile=_Insomnia
formatter_settings_version=12
......@@ -30,208 +30,211 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class AccountEvent extends GenericEntity {
private static final long serialVersionUID = 2588419823225148100L;
@Column(name = "cash", nullable = false)
private boolean cash = false;
/**
* What 1 unit of this product costs.
*/
@Column(name = "unit_price", nullable = false, precision = 24, scale = 4)
private BigDecimal unitPrice;
/**
* The units of the product, eg 1.345 (l), 5 (units) 888.32 (g)..
*/
@Column(name = "quantity", nullable = false, precision = 24, scale = 4)
private BigDecimal quantity;
/**
* The time this AccountEvent is created.
*/
@Column(name = "event_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Calendar eventTime = Calendar.getInstance();
/**
* Is the product delivered to the user.
*/
@Column(name = "delivered")
@Temporal(TemporalType.TIMESTAMP)
private Calendar delivered;
@Column(name = "delivered_count", nullable = false, precision = 24, scale = 4)
private BigDecimal deliveredCount = new BigDecimal(0);
/**
* If this AccountEvent is a product in foodwace, this field is a reference
* to that foodwave.
*/
@JoinColumn(name = "food_wave_id", referencedColumnName = FoodWave.ID_COLUMN)
@ManyToOne
private FoodWave foodWave;
/**
* The product user has acquired and this this AccountEvent is a reference
* to.
*/
@JoinColumn(name = "product_id", referencedColumnName = Product.ID_COLUMN, nullable = false)
@ManyToOne(optional = false)
private Product product;
/**
* The user that bought the products.
*/
@JoinColumn(name = "eventuser_id", referencedColumnName = EventUser.ID_COLUMN, nullable = false)
@ManyToOne(optional = false)
private EventUser user;
/**
* Who sold the items to the user.
*/
@JoinColumn(name = "seller_eventuser_id", referencedColumnName = EventUser.ID_COLUMN)
@ManyToOne(optional = true)
private EventUser seller;
/**
* What discounts user has for this account event. Some magic is applied to
* calculate these.. :)
*/
@OneToMany(mappedBy = "accountEvent", cascade = CascadeType.ALL)
private List<DiscountInstance> discountInstances = new ArrayList<DiscountInstance>();
/**
* When user has paid a bill a Account event for product "Credit" is created
* and reference to that bill is here..
*/
@OneToOne(mappedBy = "accountEvent")
private Bill bill;
@Lob
private String description;
public BigDecimal getTotal() {
return getQuantity().multiply(getUnitPrice());
}
public AccountEvent() {
}
public AccountEvent(EventUser u, Product prod, BigDecimal unitPrice, BigDecimal quantity, Calendar eventTime) {
this.setUnitPrice(unitPrice);
this.setQuantity(quantity);
this.product = prod;
this.eventTime = eventTime;
this.user = u;
}
public Calendar getEventTime() {
return eventTime;
}
public void setEventTime(Calendar eventTime) {
this.eventTime = eventTime;
}
public Calendar getDelivered() {
return delivered;
}
public void setDelivered(Calendar delivered) {
this.delivered = delivered;
}
public EventUser getUser() {
return user;
}
public void setUser(EventUser usersId) {
this.user = usersId;
}
public List<DiscountInstance> getDiscountInstances() {
return discountInstances;
}
public void setDiscountInstances(List<DiscountInstance> discountInstanceList) {
this.discountInstances = discountInstanceList;
}
public void setFoodWave(FoodWave foodWave) {
this.foodWave = foodWave;
}
public FoodWave getFoodWave() {
return foodWave;
}
public void setProduct(Product product) {
this.product = product;
}
public Product getProduct() {
return product;
}
public void setSeller(EventUser seller) {
this.seller = seller;
}
public EventUser getSeller() {
return seller;
}
public void setBill(Bill bill) {
this.bill = bill;
}
public Bill getBill() {
return bill;
}
public void setUnitPrice(BigDecimal unitPrice) {
this.unitPrice = unitPrice;
}
public BigDecimal getUnitPrice() {
return unitPrice;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getQuantity() {
return quantity;
}
public void setCash(boolean cash) {
this.cash = cash;
}
public boolean isCash() {
return cash;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getDeliveredCount() {
return deliveredCount;
}
private static final long serialVersionUID = 2588419823225148100L;
@Column(name = "cash", nullable = false)
private boolean cash = false;
/**
* What 1 unit of this product costs.
*/
@Column(name = "unit_price", nullable = false, precision = 24, scale = 4)
private BigDecimal unitPrice;
/**
* The units of the product, eg 1.345 (l), 5 (units) 888.32 (g)..
*/
@Column(name = "quantity", nullable = false, precision = 24, scale = 4)
private BigDecimal quantity;
/**
* The time this AccountEvent is created.
*/
@Column(name = "event_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Calendar eventTime = Calendar.getInstance();
/**
* Is the product delivered to the user.
*/
@Column(name = "delivered")
@Temporal(TemporalType.TIMESTAMP)
private Calendar delivered;
@Column(name = "delivered_count", nullable = false, precision = 24, scale = 4)
private BigDecimal deliveredCount = new BigDecimal(0);
/**
* If this AccountEvent is a product in foodwace, this field is a reference
* to that foodwave.
*/
@JoinColumn(name = "food_wave_id", referencedColumnName = FoodWave.ID_COLUMN)
@ManyToOne
private FoodWave foodWave;
/**
* The product user has acquired and this this AccountEvent is a reference
* to.
*/
@JoinColumn(name = "product_id", referencedColumnName = Product.ID_COLUMN, nullable = false)
@ManyToOne(optional = false)
private Product product;
/**
* The user that bought the products.
*/
@JoinColumn(name = "eventuser_id", referencedColumnName = EventUser.ID_COLUMN, nullable = false)
@ManyToOne(optional = false)
private EventUser user;
/**
* Who sold the items to the user.
*/
@JoinColumn(name = "seller_eventuser_id", referencedColumnName = EventUser.ID_COLUMN)
@ManyToOne(optional = true)
private EventUser seller;
/**
* What discounts user has for this account event. Some magic is applied to
* calculate these.. :)
*/
@OneToMany(mappedBy = "accountEvent", cascade = CascadeType.ALL)
private List<DiscountInstance> discountInstances = new ArrayList<DiscountInstance>();
/**
* When user has paid a bill a Account event for product "Credit" is created
* and reference to that bill is here..
*/
@OneToOne(mappedBy = "accountEvent")
private Bill bill;
@Lob
private String description;
public BigDecimal getTotal() {
return getQuantity().multiply(getUnitPrice());
}
public AccountEvent() {
}
public AccountEvent(EventUser u, Product prod, BigDecimal unitPrice, BigDecimal quantity, Calendar eventTime) {
if (!u.getEvent().equals(prod.getEvent())) {
throw new RuntimeException("User and product are not in the same event!");
}
this.setUnitPrice(unitPrice);
this.setQuantity(quantity);
this.product = prod;
this.eventTime = eventTime;
this.user = u;
}
public Calendar getEventTime() {
return eventTime;
}
public void setEventTime(Calendar eventTime) {
this.eventTime = eventTime;
}
public Calendar getDelivered() {
return delivered;
}
public void setDelivered(Calendar delivered) {
this.delivered = delivered;
}
public EventUser getUser() {
return user;
}
public void setUser(EventUser usersId) {
this.user = usersId;
}
public List<DiscountInstance> getDiscountInstances() {
return discountInstances;
}
public void setDiscountInstances(List<DiscountInstance> discountInstanceList) {
this.discountInstances = discountInstanceList;
}
public void setFoodWave(FoodWave foodWave) {
this.foodWave = foodWave;
}
public FoodWave getFoodWave() {
return foodWave;
}
public void setProduct(Product product) {
this.product = product;
}
public Product getProduct() {
return product;
}
public void setSeller(EventUser seller) {
this.seller = seller;
}
public EventUser getSeller() {
return seller;
}
public void setBill(Bill bill) {
this.bill = bill;
}
public Bill getBill() {
return bill;
}
public void setUnitPrice(BigDecimal unitPrice) {
this.unitPrice = unitPrice;
}
public BigDecimal getUnitPrice() {
return unitPrice;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getQuantity() {
return quantity;
}
public void setCash(boolean cash) {
this.cash = cash;
}
public boolean isCash() {
return cash;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getDeliveredCount() {
return deliveredCount;
}
public void setDeliveredCount(BigDecimal deliveredCount) {
this.deliveredCount = deliveredCount;
}
public void setDeliveredCount(BigDecimal deliveredCount) {
this.deliveredCount = deliveredCount;
}
public boolean isEventDelivered() {
return (delivered != null);
}
public boolean isEventDelivered() {
return (delivered != null);
}
}
package fi.codecrew.moya.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
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 {
USERKEY, ORGAUTH
}
/**
*
*/
private static final long serialVersionUID = -2283975589693287217L;
@JoinColumn(nullable = false, updatable = false)
@ManyToOne
private User developer;
@Lob
@Column(nullable = false, unique = true)
private String applicationKey;
@Column(nullable = false, unique = true)
private String name;
@Lob
private String description;
@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date created;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private AuthType authtype = AuthType.USERKEY;
@Column(nullable = false)
private boolean enabled = true;
@Enumerated(EnumType.STRING)
private ReaderType readerType;
@OneToMany(mappedBy = "application")
private List<ApiApplicationInstance> instances = new ArrayList<>();
public User getDeveloper() {
return developer;
}
public void setDeveloper(User developer) {
this.developer = developer;
}
public String getApplicationKey() {
return applicationKey;
}
public void setApplicationKey(String applicationKey) {
this.applicationKey = applicationKey;
}
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 Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public AuthType getAuthtype() {
return authtype;
}
public void setAuthtype(AuthType authtype) {
this.authtype = authtype;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public ReaderType getReaderType() {
return readerType;
}
public void setReaderType(ReaderType readerType) {
this.readerType = readerType;
}
public List<ApiApplicationInstance> getInstances() {
return instances;
}
public void setInstances(List<ApiApplicationInstance> instances) {
this.instances = instances;
}
}
package fi.codecrew.moya.model;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name = "api_application_instances", uniqueConstraints = @UniqueConstraint(columnNames = {
ApiApplicationInstance.APPLICATION_ID_COLUMN,
ApiApplicationInstance.AUTHNAME_COLUMN
}))
public class ApiApplicationInstance extends GenericEntity {
public static final String UNIQUE_KEY_COLUMN = "secret_key";
public static final String APPLICATION_ID_COLUMN = "application_id";
private static final long serialVersionUID = 8311790714131060263L;
public static final String AUTHNAME_COLUMN = "authname";
@JoinColumn(nullable = false, name = APPLICATION_ID_COLUMN, updatable = false)
@ManyToOne()
private ApiApplication application;
@Column(nullable = false)
private boolean enabled = true;
@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date created;
@Column(nullable = false, updatable = false, name = AUTHNAME_COLUMN)
private String authname;
@Lob
private String name;
@OneToMany()
private List<Reader> readers;
@Lob
private String notes;
@JoinColumn(nullable = true)
@ManyToOne
private EventUser eventuser;
@Lob
@Column(name = UNIQUE_KEY_COLUMN, nullable = false, updatable = false)
private String secretKey;
public ApiApplication getApplication() {
return application;
}
public void setApplication(ApiApplication application) {
this.application = application;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Reader> getReaders() {
return readers;
}
public void setReaders(List<Reader> readers) {
this.readers = readers;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public EventUser getEventuser() {
return eventuser;
}
public void setEventuser(EventUser eventuser) {
this.eventuser = eventuser;
}
public String getAuthname() {
return authname;
}
public void setAuthname(String authname) {
this.authname = authname;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
}
......@@ -9,14 +9,59 @@ import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "card_barcode")
@Table(name = "card_code")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CardBarcode extends GenericEntity {
private static final long serialVersionUID = 4771609802672223277L;
public class CardCode extends GenericEntity {
private static final long serialVersionUID = 307145499023412008L;
private ReaderType type;
private String code;
public static final String EVENT_ID_COLUMN = "event_id";
@ManyToOne
@JoinColumn(name = EVENT_ID_COLUMN, nullable = false)
private LanEvent event;
@ManyToOne()
@JoinColumn(name = "printed_cards_id")
private PrintedCard printedCard;
public CardCode(PrintedCard card, ReaderType type, String code) {
this.printedCard = card;
this.type = type;
this.code = code;
}
public CardCode() {
}
public ReaderType getType() {
return type;
}
public void setType(ReaderType type) {
this.type = type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public LanEvent getEvent() {
return event;
}
public void setEvent(LanEvent event) {
this.event = event;
}
public PrintedCard getPrintedCard() {
return printedCard;
......@@ -25,4 +70,7 @@ public class CardBarcode extends GenericEntity {
public void setPrintedCard(PrintedCard printedCard) {
this.printedCard = printedCard;
}
}
......@@ -5,7 +5,6 @@
package fi.codecrew.moya.model;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
......@@ -31,200 +30,212 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@Table(name = "compos")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Compo extends GenericEntity {
private static final long serialVersionUID = 2L;
/**
* Name of the competition.
*/
@Column(name = "compo_name", nullable = false)
private String name;
public static final String EVENT_ID_COLUMN = "event_id";
@ManyToOne()
@JoinColumn(name = EVENT_ID_COLUMN, nullable = false)
private LanEvent event;
/**
* Start time of the competition Submitting entries should be disabled after
* this time.
*/
@Column(name = "compo_start")
@Temporal(TemporalType.TIMESTAMP)
private Date startTime;
@Column(name = "compo_end")
@Temporal(TemporalType.TIMESTAMP)
private Date endTime;
/**
* When the voting should start
*
* @see {@link #holdVoting}
*/
@Column(name = "vote_start")
@Temporal(TemporalType.TIMESTAMP)
private Date voteStart;
@Column(name = "vote_end")
@Temporal(TemporalType.TIMESTAMP)
private Date voteEnd;
@Column(name = "submit_start")
@Temporal(TemporalType.TIMESTAMP)
private Date submitStart;
@Column(name = "submit_end")
@Temporal(TemporalType.TIMESTAMP)
private Date submitEnd;
@Lob
@Column(name = "description")
private String description;
@Column(name = "max_participant_count")
private int maxParticipantCount;
/**
* If ( for some unimaginable reason ) compo is delayed hold voting can be
* used to postpone the start of the voting from the time specified in
* {@link #voteStart}
*/
@Column(name = "hold_voting", nullable = false)
private boolean holdVoting = true;
/**
* Entries submitted to participate this compo.
*/
@OneToMany(cascade = CascadeType.ALL, mappedBy = "compo")
@OrderBy("sort")
private List<CompoEntry> compoEntries;
public Compo(String compoName, boolean holdVoting) {
this();
this.name = compoName;
this.holdVoting = holdVoting;
}
public boolean isSubmit()
{
Calendar now = Calendar.getInstance();
return now.after(getSubmitStart()) && now.before(getSubmitEnd());
}
public boolean isVote()
{
Calendar now = Calendar.getInstance();
return !getHoldVoting() &&
now.after(getVoteStart()) &&
now.before(getVoteEnd());
}
public Compo() {
super();
}
public String getName() {
return name;
}
public void setName(String compoName) {
this.name = compoName;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date compoStart) {
this.startTime = compoStart;
}
public Date getVoteStart() {
return voteStart;
}
public void setVoteStart(Date voteStart) {
this.voteStart = voteStart;
}
public Date getVoteEnd() {
return voteEnd;
}
public void setVoteEnd(Date voteEnd) {
this.voteEnd = voteEnd;
}
public Date getSubmitStart() {
return submitStart;
}
public void setSubmitStart(Date submitStart) {
this.submitStart = submitStart;
}
public Date getSubmitEnd() {
return submitEnd;
}
public void setSubmitEnd(Date submitEnd) {
this.submitEnd = submitEnd;
}
public boolean getHoldVoting() {
return holdVoting;
}
public void setHoldVoting(boolean holdVoting) {
this.holdVoting = holdVoting;
}
public List<CompoEntry> getCompoEntries() {
return compoEntries;
}
public void setCompoEntries(List<CompoEntry> compoEntryList) {
this.compoEntries = compoEntryList;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
/**
* @return the maxParticipantCount
*/
public int getMaxParticipantCount() {
return maxParticipantCount;
}
/**
* @param maxParticipantCount
* the maxParticipantCount to set
*/
public void setMaxParticipantCount(int maxParticipantCount) {
this.maxParticipantCount = maxParticipantCount;
}
public LanEvent getEvent() {
return event;
}
public void setEvent(LanEvent event) {
this.event = event;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
private static final long serialVersionUID = 2L;
/**
* Name of the competition.
*/
@Column(name = "compo_name", nullable = false)
private String name;
public static final String EVENT_ID_COLUMN = "event_id";
@ManyToOne()
@JoinColumn(name = EVENT_ID_COLUMN, nullable = false)
private LanEvent event;
/**
* Start time of the competition Submitting entries should be disabled after
* this time.
*/
@Column(name = "compo_start")
@Temporal(TemporalType.TIMESTAMP)
private Date startTime;
@Column(name = "compo_end")
@Temporal(TemporalType.TIMESTAMP)
private Date endTime;
/**
* When the voting should start
*
* @see {@link #holdVoting}
*/
@Column(name = "vote_start")
@Temporal(TemporalType.TIMESTAMP)
private Date voteStart;
@Column(name = "vote_end")
@Temporal(TemporalType.TIMESTAMP)
private Date voteEnd;
@Column(name = "submit_start")
@Temporal(TemporalType.TIMESTAMP)
private Date submitStart;
@Column(name = "submit_end")
@Temporal(TemporalType.TIMESTAMP)
private Date submitEnd;
@Lob
@Column(name = "description")
private String description;
@Column(name = "max_participant_count")
private int maxParticipantCount;
/**
* If ( for some unimaginable reason ) compo is delayed hold voting can be
* used to postpone the start of the voting from the time specified in
* {@link #voteStart}
*/
@Column(name = "hold_voting", nullable = false)
private boolean holdVoting = false;
@Column(name = "hidden", nullable = false)
private boolean hidden = false;
public boolean isHidden() {
return hidden;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
/**
* Entries submitted to participate this compo.
*/
@OneToMany(cascade = CascadeType.ALL, mappedBy = "compo")
@OrderBy("sort")
private List<CompoEntry> compoEntries;
public Compo(String compoName, boolean holdVoting) {
this();
this.name = compoName;
this.holdVoting = holdVoting;
}
public boolean isSubmit()
{
Date now = new Date();
return now.after(getSubmitStart()) && now.before(getSubmitEnd());
}
public boolean isVote()
{
Date now = new Date();
return !getHoldVoting() &&
now.after(getVoteStart()) &&
now.before(getVoteEnd());
}
public Compo() {
super();
}
public String getName() {
return name;
}
public void setName(String compoName) {
this.name = compoName;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date compoStart) {
this.startTime = compoStart;
}
public Date getVoteStart() {
return voteStart;
}
public void setVoteStart(Date voteStart) {
this.voteStart = voteStart;
}
public Date getVoteEnd() {
return voteEnd;
}
public void setVoteEnd(Date voteEnd) {
this.voteEnd = voteEnd;
}
public Date getSubmitStart() {
return submitStart;
}
public void setSubmitStart(Date submitStart) {
this.submitStart = submitStart;
}
public Date getSubmitEnd() {
return submitEnd;
}
public void setSubmitEnd(Date submitEnd) {
this.submitEnd = submitEnd;
}
public boolean getHoldVoting() {
return holdVoting;
}
public void setHoldVoting(boolean holdVoting) {
this.holdVoting = holdVoting;
}
public List<CompoEntry> getCompoEntries() {
return compoEntries;
}
public void setCompoEntries(List<CompoEntry> compoEntryList) {
this.compoEntries = compoEntryList;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
/**
* @return the maxParticipantCount
*/
public int getMaxParticipantCount() {
return maxParticipantCount;
}
/**
* @param maxParticipantCount
* the maxParticipantCount to set
*/
public void setMaxParticipantCount(int maxParticipantCount) {
this.maxParticipantCount = maxParticipantCount;
}
public LanEvent getEvent() {
return event;
}
public void setEvent(LanEvent event) {
this.event = event;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
}
......@@ -11,7 +11,6 @@ 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;
......@@ -23,7 +22,6 @@ import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
/**
*
......@@ -32,170 +30,155 @@ import org.eclipse.persistence.annotations.PrivateOwned;
@Table(name = "compo_entries")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CompoEntry extends GenericEntity {
private static final long serialVersionUID = 2L;
private static final long serialVersionUID = 2L;
@JoinColumn(name = "compo_id", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false)
private Compo compo;
@JoinColumn(name = "compo_id", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false)
private Compo compo;
@Column(name = "entry_created", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Calendar created = Calendar.getInstance();
@Column(name = "entry_created", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Calendar created = Calendar.getInstance();
@Column(name = "title", nullable = false)
private String title = "";
@Column(name = "author")
private String author = "";
@Lob
@Column(name = "notes")
private String notes = "";
@Lob
@Column(name = "screen_message")
private String screenMessage = "";
@Column(name = "sort")
private Integer sort = 10;
@Column(name = "title", nullable = false)
private String title = "";
@Column(name = "author")
private String author = "";
@Lob
@Column(name = "notes")
private String notes = "";
@Lob
@Column(name = "screen_message")
private String screenMessage = "";
@Column(name = "sort")
private Integer sort = 10;
@Column(name = "final_position")
private Integer finalPosition;
@JoinColumn(name = "current_file_id", referencedColumnName = CompoEntryFile.ID_COLUMN)
@OneToOne
private CompoEntryFile currentFile;
@OneToMany(mappedBy = "compoEntry")
private List<Vote> votes;
@PrivateOwned
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", fetch = FetchType.LAZY)
private List<CompoEntryFile> files;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entry")
private List<CompoEntryParticipant> participants;
@JoinColumn(name = "creator_eventuser_id", referencedColumnName = EventUser.ID_COLUMN, nullable = false)
@ManyToOne
private EventUser creator;
public Integer getVotetotal()
{
int votetotal = 0;
for (Vote v : getVotes()) {
votetotal += v.getScore();
}
return votetotal;
}
public CompoEntry() {
super();
}
public Calendar getCreated() {
return created;
}
public void setCreated(Calendar entryCreated) {
this.created = entryCreated;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getScreenMessage() {
return screenMessage;
}
public void setScreenMessage(String screenMessage) {
this.screenMessage = screenMessage;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public List<Vote> getVotes() {
return votes;
}
public void setVotes(List<Vote> voteList) {
this.votes = voteList;
}
public List<CompoEntryFile> getFiles() {
return files;
}
public void setFiles(List<CompoEntryFile> compoEntryFileList) {
this.files = compoEntryFileList;
}
public List<CompoEntryParticipant> getParticipants() {
return participants;
}
public void setParticipants(
List<CompoEntryParticipant> compoEntryParticipantList) {
this.participants = compoEntryParticipantList;
}
public Compo getCompo() {
return compo;
}
public void setCompo(Compo composId) {
this.compo = composId;
}
public EventUser getCreator() {
return creator;
}
public void setCreator(EventUser creator) {
this.creator = creator;
}
public void setFinalPosition(Integer finalPosition) {
this.finalPosition = finalPosition;
}
public Integer getFinalPosition() {
return finalPosition;
}
public void setCurrentFile(CompoEntryFile currentFile) {
this.currentFile = currentFile;
}
public CompoEntryFile getCurrentFile() {
return currentFile;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Column(name = "final_position")
private Integer finalPosition;
@JoinColumn(name = "current_file_id", referencedColumnName = CompoEntryFile.ID_COLUMN)
@OneToOne
private CompoEntryFile currentFile;
@OneToMany(mappedBy = "compoEntry")
private List<Vote> votes;
//
// @PrivateOwned
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", fetch =
// FetchType.LAZY)
// private List<CompoEntryFile> files;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entry")
private List<CompoEntryParticipant> participants;
@JoinColumn(name = "creator_eventuser_id", referencedColumnName = EventUser.ID_COLUMN, nullable = false)
@ManyToOne
private EventUser creator;
public Integer getVotetotal()
{
int votetotal = 0;
for (Vote v : getVotes()) {
votetotal += v.getScore();
}
return votetotal;
}
public CompoEntry() {
super();
}
public Calendar getCreated() {
return created;
}
public void setCreated(Calendar entryCreated) {
this.created = entryCreated;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getScreenMessage() {
return screenMessage;
}
public void setScreenMessage(String screenMessage) {
this.screenMessage = screenMessage;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public List<Vote> getVotes() {
return votes;
}
public void setVotes(List<Vote> voteList) {
this.votes = voteList;
}
public List<CompoEntryParticipant> getParticipants() {
return participants;
}
public void setParticipants(
List<CompoEntryParticipant> compoEntryParticipantList) {
this.participants = compoEntryParticipantList;
}
public Compo getCompo() {
return compo;
}
public void setCompo(Compo composId) {
this.compo = composId;
}
public EventUser getCreator() {
return creator;
}
public void setCreator(EventUser creator) {
this.creator = creator;
}
public void setFinalPosition(Integer finalPosition) {
this.finalPosition = finalPosition;
}
public Integer getFinalPosition() {
return finalPosition;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
......@@ -5,10 +5,14 @@
package fi.codecrew.moya.model;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
......@@ -16,8 +20,11 @@ import javax.persistence.Table;
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;
/**
*
......@@ -26,94 +33,110 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@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")
private String mimeType;
@Column(name = "file_name")
private String fileName;
@Lob
@Column(name = "description")
private String description;
@Column(name = "hash")
private String hash;
@Lob
@Column(name = "file_data")
private byte[] fileData;
@Column(name = "uploaded", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Calendar uploaded = Calendar.getInstance();
@JoinColumn(name = "entry_id", referencedColumnName = "id", nullable = false, updatable = false)
@ManyToOne(optional = false)
private CompoEntry entry;
public CompoEntryFile() {
super();
}
public CompoEntryFile(CompoEntry entry) {
this.entry = entry;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public byte[] getFileData() {
return fileData;
}
public void setFileData(byte[] fileData) {
this.fileData = fileData;
}
public Calendar getUploaded() {
return uploaded;
}
public void setUploaded(Calendar uploaded) {
this.uploaded = uploaded;
}
public CompoEntry getEntriesId() {
return entry;
}
public void setEntriesId(CompoEntry entriesId) {
this.entry = entriesId;
}
private static final long serialVersionUID = 1L;
@Column(name = "mime_type")
private String mimeType;
@Column(name = "file_name")
private String fileName;
@Lob
@Column(name = "description")
private String description;
@Column(name = "hash", updatable = false)
private String hash;
@Lob
@Column(name = "file_data", updatable = false)
@Basic(fetch = FetchType.LAZY)
private byte[] fileData;
@Column(name = "uploaded", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Calendar uploaded = Calendar.getInstance();
@JoinColumn(name = "entry_id", referencedColumnName = "id", nullable = false, updatable = false)
@ManyToOne(optional = false)
private CompoEntry entry;
private static final Logger logger = LoggerFactory.getLogger(CompoEntryFile.class);
public CompoEntryFile() {
super();
}
public CompoEntryFile(CompoEntry entry) {
this.entry = entry;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public byte[] getFileData() {
return fileData;
}
public void setFileData(byte[] fileData) {
this.fileData = fileData;
this.hash = getShaChecksum(fileData);
}
public Calendar getUploaded() {
return uploaded;
}
public void setUploaded(Calendar uploaded) {
this.uploaded = uploaded;
}
public CompoEntry getEntriesId() {
return entry;
}
public void setEntriesId(CompoEntry entriesId) {
this.entry = entriesId;
}
public static String getShaChecksum(byte[] data)
{
String ret = "ERROR CALCULATING CHECKSUM!";
try {
MessageDigest algo = MessageDigest.getInstance("SHA");
algo.update(data);
ret = new String(Hex.encodeHex(algo.digest())).toLowerCase();
} catch (NoSuchAlgorithmException e) {
logger.warn("Error calculating checksum", e);
}
return ret;
}
}
......@@ -8,6 +8,11 @@ public enum LanEventPrivatePropertyKey {
CHECKOUT_FI_MERCHANT_PASSWORD(Type.TEXT, null),
CHECKOUT_FI_MERCHANT_ID(Type.TEXT, null),
CHECKOUT_FI_KEY_EXPIRE(Type.DATE, null),
LDAP_URL(Type.TEXT, null),
LDAP_BIND_DN(Type.TEXT, null),
LDAP_BIND_PW(Type.TEXT, null),
LDAP_USER_OU(Type.TEXT, null),
LDAP_GROUP_OU(Type.TEXT, null),
;
private enum Type {
......
package fi.codecrew.moya.model;
public enum LanEventPropertyKey {
EVENT_LOGO(Type.DATA, null),
INVITEMAIL_SUBJECT(Type.TEXT, "Invitation to Moya Online Youth Accumulator"),
INVITEMAIL_CONTENT(Type.TEXT, "You have been invited to an event by {1}.\n\nYou can register to intranet at: {0}."),
BILL_PAID_MAIL_SUBJECT(Type.TEXT, "[{0}] Lasku merkitty maksetuksi"),
BILL_PAID_MAIL_CONTENT(Type.TEXT, "Laskusi numero {0} on merkitty maksetuksi. Voit nyt siirtyä lippukauppaan varamaan haluamasi paikat. Tervetuloa tapahtumaan!"),
PORTAL_EMAIL_ADDRESS(Type.TEXT, "moya@codecrew.fi"),
PORTAL_EMAIL_NAME(Type.TEXT, "Moya Online Youth Accumulator"),
EVENT_LOGO(Type.DATA, null),
INVITEMAIL_SUBJECT(Type.TEXT, "Invitation to Moya Online Youth Accumulator"),
INVITEMAIL_CONTENT(Type.TEXT, "You have been invited to an event by {1}.\n\nYou can register to intranet at: {0}."),
BILL_PAID_MAIL_SUBJECT(Type.TEXT, "[{0}] Lasku merkitty maksetuksi"),
BILL_PAID_MAIL_CONTENT(Type.TEXT, "Laskusi numero {0} on merkitty maksetuksi. Voit nyt siirtyä lippukauppaan varamaan haluamasi paikat. Tervetuloa tapahtumaan!"),
PORTAL_EMAIL_ADDRESS(Type.TEXT, "moya@codecrew.fi"),
PORTAL_EMAIL_NAME(Type.TEXT, "Moya Online Youth Accumulator"),
ADMIN_MAIL(Type.TEXT, "moya@codecrew.fi"),
EVENT_LAYOUT(Type.TEXT, "template1"),
SHOP_DEFAULT_CASH(Type.BOOL, null),
PLACECODE_FROM_USER(Type.BOOL, "1"),
PLACECODE_PRINT_ONLY_OWN(Type.BOOL, null),
CHECK_BILL_STATS_PERMISSION(Type.BOOL, null),
GATHER_OTHER_BILL_INFO(Type.BOOL, null),
ALLOW_BILLING(Type.BOOL, null),
BILL_EXPIRE_HOURS(Type.LONG, "168"),
TEMPLATE_PROPERTY1(Type.TEXT, null),
TEMPLATE_PROPERTY2(Type.TEXT, null),
TEMPLATE_PROPERTY3(Type.TEXT, null),
TEMPLATE_PROPERTY4(Type.TEXT, null),
TEMPLATE_PROPERTY5(Type.TEXT, null),
ADMIN_MAIL(Type.TEXT, "moya@codecrew.fi"),
EVENT_LAYOUT(Type.TEXT, "template1"),
SHOP_DEFAULT_CASH(Type.BOOL, null),
PLACECODE_FROM_USER(Type.BOOL, "1"),
PLACECODE_PRINT_ONLY_OWN(Type.BOOL, null),
CHECK_BILL_STATS_PERMISSION(Type.BOOL, null),
GATHER_OTHER_BILL_INFO(Type.BOOL, null),
ALLOW_BILLING(Type.BOOL, null),
BILL_EXPIRE_HOURS(Type.LONG, "168"),
TEMPLATE_PROPERTY1(Type.TEXT, null),
TEMPLATE_PROPERTY2(Type.TEXT, null),
TEMPLATE_PROPERTY3(Type.TEXT, null),
TEMPLATE_PROPERTY4(Type.TEXT, null),
TEMPLATE_PROPERTY5(Type.TEXT, null),
INVITE_ONLY_EVENT(Type.BOOL, null),
;
;
private enum Type {
TEXT, DATE, DATA, BOOL, LONG
};
private enum Type {
TEXT, DATE, DATA, BOOL, LONG
};
private final String defaultvalue;
private final Type type;
private final String defaultvalue;
private final Type type;
public boolean isText() {
return Type.TEXT.equals(type);
}
public boolean isText() {
return Type.TEXT.equals(type);
}
public boolean isDate() {
return Type.DATE.equals(type);
}
public boolean isDate() {
return Type.DATE.equals(type);
}
public boolean isData() {
return Type.DATA.equals(type);
}
public boolean isData() {
return Type.DATA.equals(type);
}
public boolean isBoolean() {
return Type.BOOL.equals(type);
}
public boolean isLong() {
return Type.LONG.equals(type);
}
public boolean isBoolean() {
return Type.BOOL.equals(type);
}
private LanEventPropertyKey(Type t, String def)
{
this.type = t;
defaultvalue = def;
}
public boolean isLong() {
return Type.LONG.equals(type);
}
public String getDefaultvalue() {
return defaultvalue;
}
private LanEventPropertyKey(Type t, String def)
{
this.type = t;
defaultvalue = def;
}
public Type getType() {
return type;
}
public String getDefaultvalue() {
return defaultvalue;
}
public Type getType() {
return type;
}
}
......@@ -57,6 +57,28 @@ public class OrgRole extends GenericEntity {
@ManyToMany(mappedBy = "orgRoles")
private List<Role> eventRoles;
@Column(name = "ldap_role", nullable = false)
private boolean ldapRole = false;
@Column(name = "ldap_weight", nullable = false)
private int ldapWeight = 100;
public boolean isLdapRole() {
return ldapRole;
}
public void setLdapRole(boolean ldapRole) {
this.ldapRole = ldapRole;
}
public int getLdapWeight() {
return ldapWeight;
}
public void setLdapWeight(int ldapWeight) {
this.ldapWeight = ldapWeight;
}
public OrgRole() {
super();
}
......
......@@ -51,19 +51,19 @@ public class PrintedCard extends GenericEntity {
@Temporal(TemporalType.TIMESTAMP)
private Calendar printTime;
@Column(name = "barcode")
private String barcode;
@Column(name = "card_enabled", nullable = false)
private boolean enabled = true;
@Column(name = "rfid_uid")
private String rfidUid;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "printedCard")
private List<ReaderEvent> readerEvents = new ArrayList<ReaderEvent>();
@OneToMany(cascade = CascadeType.ALL, mappedBy = "printedCard")
private List<CardCode> cardCodes = new ArrayList<CardCode>();
@Column(name = "print_count", nullable = false)
@Column(name = "print_count", nullable = false)
private int printCount = 0;
@JoinColumn(name = "current_location_id", referencedColumnName = "id")
......@@ -112,13 +112,6 @@ public class PrintedCard extends GenericEntity {
this.printTime = printTime;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public boolean getEnabled() {
return enabled;
......@@ -128,14 +121,6 @@ public class PrintedCard extends GenericEntity {
this.enabled = cardEnabled;
}
public String getRfidUid() {
return rfidUid;
}
public void setRfidUid(String rfidUid) {
this.rfidUid = rfidUid;
}
public List<ReaderEvent> getReaderEvents() {
return readerEvents;
}
......@@ -152,6 +137,17 @@ public class PrintedCard extends GenericEntity {
this.currentLocation = currentLocation;
}
public List<CardCode> getCardCodes() {
return cardCodes;
}
public void setCardCodes(List<CardCode> cardCodes) {
this.cardCodes = cardCodes;
}
public EventUser getUser() {
return user;
}
......@@ -175,34 +171,7 @@ public class PrintedCard extends GenericEntity {
public int getPrintCount() {
return printCount;
}
public static final Comparator<PrintedCard> GAMEPOINT_COMPARATOR = new Comparator<PrintedCard>() {
@Override
public int compare(PrintedCard o1, PrintedCard o2) {
int ret = o2.getGamepoints().compareTo(o1.getGamepoints());
if (ret == 0 && o1.getUser().getUser().getNick() != null && o2.getUser().getUser().getNick() != null)
{
ret = o1.getUser().getUser().getNick().compareTo(o2.getUser().getUser().getNick());
}
return ret;
}
};
@Transient
private Integer gamepoints = null;
public Integer getGamepoints() {
if (gamepoints == null) {
Integer ret = 0;
for (ReaderEvent re : this.getReaderEvents()) {
ret += re.getGamePoint();
}
gamepoints = ret;
}
return gamepoints;
}
public CardState getCardState() {
return cardState;
......@@ -212,21 +181,4 @@ public class PrintedCard extends GenericEntity {
this.cardState = cardState;
}
@Transient
private transient ListDataModel<ReaderEvent> revents;
public ListDataModel<ReaderEvent> getGameCards() {
if (revents == null) {
List<ReaderEvent> ev = this.getReaderEvents();
ArrayList<ReaderEvent> ret = new ArrayList<ReaderEvent>();
for (ReaderEvent e : ev) {
if (e.getGamePoint() > 0) {
ret.add(e);
}
}
revents = new ListDataModel<ReaderEvent>(ret);
}
return revents;
}
}
package fi.codecrew.moya.model;
import java.util.Calendar;
import java.beans.Transient;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
......@@ -23,121 +25,181 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class ReaderEvent extends GenericEntity {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
@Column(name = "event_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date time;
@Column(name = "event_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date time;
@Column(name = "event_updated")
@Temporal(TemporalType.TIMESTAMP)
private Date updatetime;
@Column(name = "value")
private String value;
@Lob
@Column(name = "notes")
private String notes;
@Column(nullable = false)
private Integer gamePoint = 0;
@JoinColumn(name = "printed_cards_id", referencedColumnName = "id", nullable = true, updatable = false)
@ManyToOne(optional = false)
private PrintedCard printedCard;
@JoinColumn(name = "readers_id", referencedColumnName = "id", nullable = false, updatable = false)
@ManyToOne(optional = false)
private Reader reader;
public ReaderEvent(Calendar eventTime, PrintedCard card, Reader reader) {
this.time = eventTime.getTime();
this.printedCard = card;
this.reader = reader;
}
public ReaderEvent() {
super();
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Date getTime() {
return time;
}
public void setTime(Date eventTime) {
this.time = eventTime;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public PrintedCard getPrintedCard() {
return printedCard;
}
public void setPrintedCard(PrintedCard printedCardsId) {
this.printedCard = printedCardsId;
}
public Reader getReader() {
return reader;
}
public void setReader(Reader readersId) {
this.reader = readersId;
}
public void setGamePoint(Integer gamePoint) {
this.gamePoint = gamePoint;
}
public Integer getGamePoint() {
return gamePoint;
}
public Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
public String getSeenSince() {
Date comptime = updatetime;
if (comptime == null)
{
comptime = time;
}
long diffSec = (new Date().getTime() - comptime.getTime()) / 1000;
long secs = diffSec % 60;
long diffMin = diffSec / 60;
long mins = diffMin % 60;
long hours = diffMin / 60;
StringBuilder ret = new StringBuilder();
if (hours > 0) {
ret.append(hours).append(" h ");
}
if (hours > 0 || mins > 0) {
ret.append(mins).append(" min ");
}
ret.append(secs).append(" sec");
return ret.toString();
}
@Column(name = "event_updated")
@Temporal(TemporalType.TIMESTAMP)
private Date updatetime;
@Column(name = "value")
private String value;
@Lob
@Column(name = "notes")
private String notes;
@JoinColumn(name = "printed_cards_id", referencedColumnName = "id", nullable = true, updatable = false)
@ManyToOne()
private PrintedCard printedCard;
@JoinColumn(name = "readers_id", referencedColumnName = "id", nullable = false, updatable = false)
@ManyToOne(optional = false)
private Reader reader;
@JoinColumn(name = "event_users_id", referencedColumnName = "id", nullable = true, updatable = false)
@ManyToOne()
private EventUser user;
@JoinColumn(name = "places_id", referencedColumnName = "id", nullable = true, updatable = false)
@ManyToOne()
private Place place;
@JoinColumn(name = "products_id", referencedColumnName = "id", nullable = true, updatable = false)
@ManyToOne()
private Product product;
@Enumerated(EnumType.STRING)
private ReaderEventType type;
public ReaderEvent(Date eventTime, Reader reader, String value) {
this(eventTime, reader, value, null, null, null, null, ReaderEventType.UNKNOWN);
}
public ReaderEvent(Date eventTime, Reader reader, String value, ReaderEventType type) {
this(eventTime, reader, value, null, null, null, null, type);
}
public ReaderEvent(Date eventTime, Reader reader, String value, PrintedCard card, EventUser user, Place place, Product product, ReaderEventType type) {
this.time = eventTime;
this.reader = reader;
this.value = value;
this.user = user;
this.printedCard = card;
this.user = user;
this.place = place;
this.product = product;
if (type == null)
type = ReaderEventType.UNKNOWN;
this.type = type;
}
public ReaderEvent() {
super();
}
public EventUser getUser() {
return user;
}
public void setUser(EventUser user) {
this.user = user;
}
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public ReaderEventType getType() {
return type;
}
public void setType(ReaderEventType type) {
this.type = type;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Date getTime() {
return time;
}
public void setTime(Date eventTime) {
this.time = eventTime;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public PrintedCard getPrintedCard() {
return printedCard;
}
public void setPrintedCard(PrintedCard printedCardsId) {
this.printedCard = printedCardsId;
}
public Reader getReader() {
return reader;
}
public void setReader(Reader readersId) {
this.reader = readersId;
}
public Date getUpdatetime() {
if (updatetime == null)
return time;
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
@Transient
public String getSeenSince() {
return "" + ((getUpdatetime().getTime() / 1000) / 60) +" min." ;
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!