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 @@ ...@@ -7,3 +7,4 @@
*~ *~
.metadata .metadata
/code/*/target/ /code/*/target/
/code/*/test-output/
No preview for this file type
...@@ -86,13 +86,14 @@ public class MoyaLoginModule extends AppservPasswordLoginModule { ...@@ -86,13 +86,14 @@ public class MoyaLoginModule extends AppservPasswordLoginModule {
// Authenticate User // Authenticate User
MoyaRealm samplerealm = (MoyaRealm) _currentRealm; 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 // Login fails
throw new LoginException((new StringBuilder()) throw new LoginException((new StringBuilder())
.append("moya realm:Login Failed for user ") .append("moya realm:Login Failed for user ")
.append(_username).toString()); .append(_username).toString());
} }
_username = authResult.getUsername();
// Login succeeds // Login succeeds
log((new StringBuilder()).append("MoyaRealm:login succeeded for ") log((new StringBuilder()).append("MoyaRealm:login succeeded for ")
.append(_username).toString()); .append(_username).toString());
...@@ -100,7 +101,7 @@ public class MoyaLoginModule extends AppservPasswordLoginModule { ...@@ -100,7 +101,7 @@ public class MoyaLoginModule extends AppservPasswordLoginModule {
// Get group names for the authenticated user from the Realm class // Get group names for the authenticated user from the Realm class
Enumeration<String> enumeration = null; Enumeration<String> enumeration = null;
try { try {
enumeration = samplerealm.getGroupNames(_username); enumeration = samplerealm.getGroupNames(_username, authResult.getUsertype());
} catch (InvalidOperationException invalidoperationexception) { } catch (InvalidOperationException invalidoperationexception) {
throw new LoginException( throw new LoginException(
(new StringBuilder()) (new StringBuilder())
......
...@@ -89,7 +89,7 @@ public class MoyaRealm extends AppservRealm { ...@@ -89,7 +89,7 @@ public class MoyaRealm extends AppservRealm {
*/ */
@Override @Override
public String getAuthType() { public String getAuthType() {
return "Omnia Lan system authentication Realm"; return "Moya authentication Realm";
} }
/** /**
...@@ -127,4 +127,8 @@ public class MoyaRealm extends AppservRealm { ...@@ -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 { ...@@ -13,4 +13,8 @@ public interface MoyaRealmBeanRemote {
boolean authenticate(String _username, String string); 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 { ...@@ -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 products ALTER COLUMN vat TYPE NUMERIC(4,3)" });
dbUpdates.add(new String[] { "ALTER TABLE actionlog_messages DROP COLUMN crew" }); 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[] { "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 @EJB
...@@ -61,7 +86,8 @@ public class BootstrapBean implements BootstrapBeanLocal { ...@@ -61,7 +86,8 @@ public class BootstrapBean implements BootstrapBeanLocal {
throw new RuntimeException("Sanity check failed! DB is newer than the codebase!"); throw new RuntimeException("Sanity check failed! DB is newer than the codebase!");
} }
} else { } 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 = new DBModel();
dBm.setRevision(upIdx); dBm.setRevision(upIdx);
dbModelFacade.create(dBm); dbModelFacade.create(dBm);
......
...@@ -189,10 +189,10 @@ public class CardTemplateBean implements CardTemplateBeanLocal { ...@@ -189,10 +189,10 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
public CardTemplate getUsersCardtype(EventUser user) { public CardTemplate getUsersCardtype(EventUser user) {
Set<Role> roles = userbean.localFindUsersRoles(user); Set<Role> roles = userbean.localFindUsersRoles(user);
logger.info("Checking roles {} against {}", user, roles); // logger.info("Checking roles {} against {}", user, roles);
CardTemplate greatestTemplate = null; CardTemplate greatestTemplate = null;
for (Role listrole : roles) { 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())) { if (greatestTemplate == null || (listrole.getCardTemplate() != null && greatestTemplate.getPower() < listrole.getCardTemplate().getPower())) {
greatestTemplate = listrole.getCardTemplate(); greatestTemplate = listrole.getCardTemplate();
} }
......
...@@ -138,7 +138,7 @@ public class EventBean implements EventBeanLocal { ...@@ -138,7 +138,7 @@ public class EventBean implements EventBeanLocal {
@Override @Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT }) @RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT })
public LanEvent mergeChanges(LanEvent 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."); throw new EJBAccessException("Trying to save another event.");
} }
return eventFacade.merge(event); return eventFacade.merge(event);
...@@ -187,8 +187,7 @@ public class EventBean implements EventBeanLocal { ...@@ -187,8 +187,7 @@ public class EventBean implements EventBeanLocal {
public LanEventProperty getProperty(LanEventPropertyKey property) { public LanEventProperty getProperty(LanEventPropertyKey property) {
return eventPropertyFacade.find(getCurrentEvent(), property); return eventPropertyFacade.find(getCurrentEvent(), property);
} }
@Override @Override
public long getPropertyLong(LanEventPropertyKey property) public long getPropertyLong(LanEventPropertyKey property)
{ {
...@@ -201,8 +200,6 @@ public class EventBean implements EventBeanLocal { ...@@ -201,8 +200,6 @@ public class EventBean implements EventBeanLocal {
} }
return ret; return ret;
} }
@Override @Override
public String getPropertyString(LanEventPropertyKey property) public String getPropertyString(LanEventPropertyKey property)
...@@ -266,4 +263,33 @@ public class EventBean implements EventBeanLocal { ...@@ -266,4 +263,33 @@ public class EventBean implements EventBeanLocal {
return ret; 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 { ...@@ -109,4 +109,12 @@ public class EventMapBean implements EventMapBeanLocal {
public Place updatePlace(Place place) { public Place updatePlace(Place place) {
return placefacade.merge(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; ...@@ -11,18 +11,26 @@ import javax.ejb.Stateless;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import fi.codecrew.moya.AuthenticationResult;
import fi.codecrew.moya.MoyaRealmBeanRemote; import fi.codecrew.moya.MoyaRealmBeanRemote;
import fi.codecrew.moya.enums.BortalApplication; import fi.codecrew.moya.enums.BortalApplication;
import fi.codecrew.moya.enums.apps.IAppPermission; import fi.codecrew.moya.enums.apps.IAppPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission; import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.enums.apps.UserPermission; 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.EventUserFacade;
import fi.codecrew.moya.facade.UserFacade; 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.ApplicationPermission;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEvent; 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.Role;
import fi.codecrew.moya.model.User; import fi.codecrew.moya.model.User;
import fi.codecrew.moya.utilities.PasswordFunctions;
/** /**
* Session Bean implementation class SessionHandlerBean * Session Bean implementation class SessionHandlerBean
...@@ -48,6 +56,15 @@ public class JaasBean implements MoyaRealmBeanRemote { ...@@ -48,6 +56,15 @@ public class JaasBean implements MoyaRealmBeanRemote {
@EJB @EJB
private EventBeanLocal eventbean; 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) { public EventUser tryLogin(String username, String password) {
EventUser eventUser = eventUserFacade.findByLogin(username.trim().toLowerCase()); EventUser eventUser = eventUserFacade.findByLogin(username.trim().toLowerCase());
...@@ -69,7 +86,13 @@ public class JaasBean implements MoyaRealmBeanRemote { ...@@ -69,7 +86,13 @@ public class JaasBean implements MoyaRealmBeanRemote {
eventUser = null; eventUser = null;
user = 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(); LanEvent event = eventbean.getCurrentEvent();
eventUser = new EventUser(user, event, null); eventUser = new EventUser(user, event, null);
...@@ -97,15 +120,45 @@ public class JaasBean implements MoyaRealmBeanRemote { ...@@ -97,15 +120,45 @@ public class JaasBean implements MoyaRealmBeanRemote {
// } // }
// } // }
public static enum UserType
{
USER, REST
}
@Override @Override
public boolean authenticate(String username, String password) { public AuthenticationResult authUsername(String username, String password) {
boolean ret = (tryLogin(username, password) != null);
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; return ret;
} }
@Override @Override
public Enumeration<String> getGroupNames(String user) { public boolean authenticate(String username, String password) {
logger.info("Fetching groupNames for user {} event {}", user, eventbean.getCurrentEvent().getName()); 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()); EventUser usr = eventUserFacade.findByLogin(user.toLowerCase().trim());
HashSet<String> roleset = new HashSet<String>(); HashSet<String> roleset = new HashSet<String>();
roleset.add(UserPermission.ANYUSER.getFullName()); roleset.add(UserPermission.ANYUSER.getFullName());
...@@ -119,6 +172,23 @@ public class JaasBean implements MoyaRealmBeanRemote { ...@@ -119,6 +172,23 @@ public class JaasBean implements MoyaRealmBeanRemote {
roleset.add(SpecialPermission.ANONYMOUS.name()); 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()) { if (!usr.getUser().isAnonymous()) {
// all logged in users should be able to logout :) // all logged in users should be able to logout :)
roleset.add(UserPermission.LOGOUT.name()); roleset.add(UserPermission.LOGOUT.name());
...@@ -152,8 +222,46 @@ public class JaasBean implements MoyaRealmBeanRemote { ...@@ -152,8 +222,46 @@ public class JaasBean implements MoyaRealmBeanRemote {
Vector<String> retvect = new Vector<String>(); Vector<String> retvect = new Vector<String>();
retvect.addAll(roleset); retvect.addAll(roleset);
logger.info("group names for user {}: {}", user, retvect); logger.debug("group names for user {}: {}", user, retvect);
return retvect.elements(); 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; ...@@ -20,6 +20,7 @@ import fi.codecrew.moya.enums.apps.MapPermission;
import fi.codecrew.moya.enums.apps.PollPermission; import fi.codecrew.moya.enums.apps.PollPermission;
import fi.codecrew.moya.enums.apps.ShopPermission; import fi.codecrew.moya.enums.apps.ShopPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission; 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.TournamentPermission;
import fi.codecrew.moya.enums.apps.UserPermission; import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.facade.MenuNavigationFacade; import fi.codecrew.moya.facade.MenuNavigationFacade;
...@@ -27,8 +28,17 @@ import fi.codecrew.moya.facade.MenuitemFacade; ...@@ -27,8 +28,17 @@ import fi.codecrew.moya.facade.MenuitemFacade;
import fi.codecrew.moya.model.LanEvent; import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.MenuNavigation; 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 @Stateless
@LocalBean @LocalBean
...@@ -70,7 +80,7 @@ public class MenuBean implements MenuBeanLocal { ...@@ -70,7 +80,7 @@ public class MenuBean implements MenuBeanLocal {
private synchronized void initializeMenu() { private synchronized void initializeMenu() {
//int menusort = 100; // int menusort = 100;
logger.info("Initializing new default menu"); logger.info("Initializing new default menu");
LanEvent ev = eventbean.getCurrentEvent(); LanEvent ev = eventbean.getCurrentEvent();
...@@ -83,9 +93,9 @@ public class MenuBean implements MenuBeanLocal { ...@@ -83,9 +93,9 @@ public class MenuBean implements MenuBeanLocal {
usermenu.addPage(menuitemfacade.findOrCreate("/checkout/cancel"), null).setVisible(false); usermenu.addPage(menuitemfacade.findOrCreate("/checkout/cancel"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/permissionDenied"), 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/login"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/loginError"), 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/logoutResponse"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/resetPassword"), null).setVisible(false); usermenu.addPage(menuitemfacade.findOrCreate("/auth/resetPassword"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/resetmailSent"), null).setVisible(false); usermenu.addPage(menuitemfacade.findOrCreate("/auth/resetmailSent"), null).setVisible(false);
...@@ -105,12 +115,15 @@ public class MenuBean implements MenuBeanLocal { ...@@ -105,12 +115,15 @@ public class MenuBean implements MenuBeanLocal {
userkauppa.addPage(menuitemfacade.findOrCreate("/shop/createBill"), BillPermission.CREATE_BILL); userkauppa.addPage(menuitemfacade.findOrCreate("/shop/createBill"), BillPermission.CREATE_BILL);
userkauppa.addPage(menuitemfacade.findOrCreate("/foodwave/list"), ShopPermission.SHOP_FOODWAVE); userkauppa.addPage(menuitemfacade.findOrCreate("/foodwave/list"), ShopPermission.SHOP_FOODWAVE);
userkauppa.addPage(menuitemfacade.findOrCreate("/bill/list"), BillPermission.VIEW_OWN); 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); MenuNavigation userPlaces = usermenu.addPage(null, null);
userPlaces.setKey("topnavi.userplaces"); userPlaces.setKey("topnavi.userplaces");
userPlaces.addPage(menuitemfacade.findOrCreate("/place/placemap"), MapPermission.VIEW); userPlaces.addPage(menuitemfacade.findOrCreate("/place/placemap"), MapPermission.VIEW);
userPlaces.addPage(menuitemfacade.findOrCreate("/place/myGroups"), MapPermission.BUY_PLACES); 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); MenuNavigation usercompetitions = usermenu.addPage(null, null);
usercompetitions.setKey("topnavi.competitions"); usercompetitions.setKey("topnavi.competitions");
...@@ -137,12 +150,10 @@ public class MenuBean implements MenuBeanLocal { ...@@ -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/participate_multi"), TournamentPermission.PARTICIPATE).setVisible(false);
tournaments.addPage(menuitemfacade.findOrCreate("/tournaments/addTeam"), TournamentPermission.PARTICIPATE).setVisible(false); tournaments.addPage(menuitemfacade.findOrCreate("/tournaments/addTeam"), TournamentPermission.PARTICIPATE).setVisible(false);
/* MenuNavigation createuser = usermenu.addPage(null, null);
* MenuNavigation createuser = usermenu.addPage(null, null); createuser.setKey("topnavi.createuser");
* createuser.setKey("topnavi.createuser"); createuser.addPage(menuitemfacade.findOrCreate("/user/create"), UserPermission.CREATE_NEW).setVisible(false);
* createuser.addPage(menuitemfacade.findOrCreate("/user/create"), ;
* UserPermission.CREATE_NEW);
*/
navifacade.create(usermenu); navifacade.create(usermenu);
...@@ -152,7 +163,7 @@ public class MenuBean implements MenuBeanLocal { ...@@ -152,7 +163,7 @@ public class MenuBean implements MenuBeanLocal {
MenuNavigation adminmenu = new MenuNavigation(ev, "topmenu.admin", 20); MenuNavigation adminmenu = new MenuNavigation(ev, "topmenu.admin", 20);
//user management // user management
MenuNavigation adminuser = adminmenu.addPage(null, null); MenuNavigation adminuser = adminmenu.addPage(null, null);
adminuser.setKey("topnavi.usermgmt"); adminuser.setKey("topnavi.usermgmt");
adminuser.addPage(menuitemfacade.findOrCreate("/useradmin/list"), UserPermission.VIEW_ALL); adminuser.addPage(menuitemfacade.findOrCreate("/useradmin/list"), UserPermission.VIEW_ALL);
...@@ -193,7 +204,6 @@ public class MenuBean implements MenuBeanLocal { ...@@ -193,7 +204,6 @@ public class MenuBean implements MenuBeanLocal {
adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/list"), ShopPermission.LIST_ALL_PRODUCTS); adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/list"), ShopPermission.LIST_ALL_PRODUCTS);
adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/create"), ShopPermission.MANAGE_PRODUCTS); adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/create"), ShopPermission.MANAGE_PRODUCTS);
adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/edit"), ShopPermission.MANAGE_PRODUCTS).setVisible(false); adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/edit"), ShopPermission.MANAGE_PRODUCTS).setVisible(false);
;
MenuNavigation foodnavi = adminshop.addPage(null, null); MenuNavigation foodnavi = adminshop.addPage(null, null);
foodnavi.setKey("topnavi.foodwave"); foodnavi.setKey("topnavi.foodwave");
...@@ -219,7 +229,8 @@ public class MenuBean implements MenuBeanLocal { ...@@ -219,7 +229,8 @@ public class MenuBean implements MenuBeanLocal {
MenuNavigation adminPlaces = adminmenu.addPage(null, null); MenuNavigation adminPlaces = adminmenu.addPage(null, null);
adminPlaces.setKey("topnavi.userplaces"); adminPlaces.setKey("topnavi.userplaces");
adminPlaces.addPage(menuitemfacade.findOrCreate("/place/adminPlacemap"), UserPermission.VIEW_ALL); 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); MenuNavigation mapnavi = adminPlaces.addPage(null, null);
mapnavi.setKey("topnavi.maps"); mapnavi.setKey("topnavi.maps");
...@@ -253,13 +264,7 @@ public class MenuBean implements MenuBeanLocal { ...@@ -253,13 +264,7 @@ public class MenuBean implements MenuBeanLocal {
gamenavi.addPage(menuitemfacade.findOrCreate("/license/manageCodes"), LicensePermission.MANAGE); gamenavi.addPage(menuitemfacade.findOrCreate("/license/manageCodes"), LicensePermission.MANAGE);
adminevent.addPage(menuitemfacade.findOrCreate("/eventorg/editEvent"), EventPermission.MANAGE_PROPERTIES); adminevent.addPage(menuitemfacade.findOrCreate("/eventorg/editEvent"), EventPermission.MANAGE_PROPERTIES);
adminevent.addPage(menuitemfacade.findOrCreate("/eventorg/edit"), EventPermission.MANAGE_PROPERTIES).setVisible(false);
navifacade.create(adminmenu);
//MenuNavigation shopmenu = new MenuNavigation(ev, "topnavi.shopnavi", menusort = +10);
// shopnavi.addPage(menuitemfacade.findOrCreate("/index3"),
// UserPermission.ANYUSER);
// navifacade.create(shopmenu);
MenuNavigation tournamentsadm = adminmenu.addPage(null, null); MenuNavigation tournamentsadm = adminmenu.addPage(null, null);
tournamentsadm.setKey("tournaments.menutitle"); tournamentsadm.setKey("tournaments.menutitle");
...@@ -270,6 +275,24 @@ public class MenuBean implements MenuBeanLocal { ...@@ -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/edit"), TournamentPermission.MANAGE_ALL).setVisible(false);
tournamentsadm.addPage(menuitemfacade.findOrCreate("/tournaments/admin/delete"), 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); 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, * MenuNavigation profileTopmenu = new MenuNavigation(ev,
* "topnavi.profile", menusort = +10); * "topnavi.profile", menusort = +10);
...@@ -330,6 +353,36 @@ public class MenuBean implements MenuBeanLocal { ...@@ -330,6 +353,36 @@ public class MenuBean implements MenuBeanLocal {
} }
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// OLD MENU STARTS HERE!!!
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
private synchronized void initializeOldMenu() { private synchronized void initializeOldMenu() {
LanEvent ev = eventbean.getCurrentEvent(); LanEvent ev = eventbean.getCurrentEvent();
...@@ -346,6 +399,7 @@ public class MenuBean implements MenuBeanLocal { ...@@ -346,6 +399,7 @@ public class MenuBean implements MenuBeanLocal {
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/sendResetMail"), UserPermission.LOGIN); frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/sendResetMail"), UserPermission.LOGIN);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/user/invite"), UserPermission.INVITE_USERS); frontTopnavi.addPage(menuitemfacade.findOrCreate("/user/invite"), UserPermission.INVITE_USERS);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/permissionDenied"), null).setVisible(false); 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/login"), null).setVisible(false);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/loginError"), null).setVisible(false); frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/loginError"), null).setVisible(false);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/logout"), null).setVisible(false); frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/logout"), null).setVisible(false);
......
...@@ -38,6 +38,7 @@ import fi.codecrew.moya.model.User; ...@@ -38,6 +38,7 @@ import fi.codecrew.moya.model.User;
UserPermission.S_MODIFY, UserPermission.S_MODIFY,
UserPermission.S_MODIFY_ACCOUNTEVENTS, UserPermission.S_MODIFY_ACCOUNTEVENTS,
UserPermission.S_VIEW_ACCOUNTEVENTS, UserPermission.S_VIEW_ACCOUNTEVENTS,
UserPermission.S_VIEW_OWN_ACCOUNTEVENTS,
UserPermission.S_VIEW_ALL, UserPermission.S_VIEW_ALL,
UserPermission.S_VIEW_SELF, UserPermission.S_VIEW_SELF,
UserPermission.S_WRITE_ROLES, UserPermission.S_WRITE_ROLES,
...@@ -53,7 +54,7 @@ import fi.codecrew.moya.model.User; ...@@ -53,7 +54,7 @@ import fi.codecrew.moya.model.User;
MapPermission.S_MANAGE_MAPS, MapPermission.S_MANAGE_MAPS,
MapPermission.S_MANAGE_OTHERS, MapPermission.S_MANAGE_OTHERS,
MapPermission.S_BUY_PLACES, MapPermission.S_BUY_PLACES,
// MapPermission.S_RELEASE_PLACE, // MapPermission.S_RELEASE_PLACE,
ShopPermission.S_LIST_ALL_PRODUCTS, ShopPermission.S_LIST_ALL_PRODUCTS,
ShopPermission.S_LIST_USERPRODUCTS, ShopPermission.S_LIST_USERPRODUCTS,
...@@ -165,7 +166,8 @@ public class PermissionBean implements PermissionBeanLocal { ...@@ -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 @Override
public EventUser getAnonEventUser() { public EventUser getAnonEventUser() {
......
...@@ -113,9 +113,12 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -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 { ...@@ -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 * @param place
* place to be reserved * place to be reserved
...@@ -196,24 +200,33 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -196,24 +200,33 @@ public class PlaceBean implements PlaceBeanLocal {
place = placeFacade.find(place.getId()); place = placeFacade.find(place.getId());
user = eventUserFacade.find(user.getId()); user = eventUserFacade.find(user.getId());
boolean ret = false; boolean ret = false;
if (place.isBuyable() && !place.isTaken()) {
place.setCurrentUser(user); // when admin click's place, he reserves it -> just ignore it
place.setReleaseTime(Calendar.getInstance()); if (!place.isTaken() || (permbean.hasPermission(MapPermission.MANAGE_OTHERS) && permbean.getCurrentUser().equals(place.getCurrentUser()))) {
place.getReleaseTime().add(Calendar.MINUTE, RESERVE_MINUTES); if (place.isBuyable() || permbean.hasPermission(MapPermission.MANAGE_OTHERS)) {
// Create timeout service to timeout the reserved place in if (!place.isBuyable()) {
// RESERVE_MINUTES place.setBuyable(true);
boolean foundTimeout = false;
for (Timer t : ts.getTimers()) {
if (t.getInfo().equals(PLACE_RESERVE_TIMEOUTER)) {
foundTimeout = 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; return ret;
} }
...@@ -237,10 +250,22 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -237,10 +250,22 @@ public class PlaceBean implements PlaceBeanLocal {
// logger.debug("timeouting places"); // logger.debug("timeouting places");
// placeFacade.releasePlaces(permbean.getCurrentUser()); // placeFacade.releasePlaces(permbean.getCurrentUser());
// } // }
@Override @Override
@RolesAllowed({ MapPermission.S_BUY_PLACES, MapPermission.S_MANAGE_OTHERS }) @RolesAllowed({ MapPermission.S_BUY_PLACES, MapPermission.S_MANAGE_OTHERS })
public PlaceGroup buySelectedPlaces(EventUser user) throws BortalCatchableException { 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) { if (user == null) {
user = permbean.getCurrentUser(); user = permbean.getCurrentUser();
} else { } else {
...@@ -258,18 +283,19 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -258,18 +283,19 @@ public class PlaceBean implements PlaceBeanLocal {
} }
// PlaceGroup pg = pgbean.createPlaceGroup(user); // 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); for (Entry<Product, Integer> line : getPlaceProductcount(places).entrySet()) {
BigDecimal balance = user.getAccountBalance(); productPBean.createAccountEvent(line.getKey(), new BigDecimal(line.getValue()), user, Calendar.getInstance());
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());
} }
PlaceGroup pg = new PlaceGroup(event, Calendar.getInstance(), Calendar.getInstance(), true); PlaceGroup pg = new PlaceGroup(event, Calendar.getInstance(), Calendar.getInstance(), true);
pg.setCreator(user); pg.setCreator(user);
pgfacade.create(pg); pgfacade.create(pg);
...@@ -346,12 +372,17 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -346,12 +372,17 @@ public class PlaceBean implements PlaceBeanLocal {
private static boolean isUserMember(EventUser user, Product prod) { private static boolean isUserMember(EventUser user, Product prod) {
boolean ret = false; boolean ret = false;
for (GroupMembership gm : user.getGroupMemberships()) { if (user.getGroupMemberships() != null)
if (prod.equals(gm.getPlaceReservation().getProduct())) { {
ret = true; for (GroupMembership gm : user.getGroupMemberships()) {
break;
if (gm.getPlaceReservation() != null && prod.equals(gm.getPlaceReservation().getProduct())) {
ret = true;
break;
}
} }
} }
return ret; return ret;
} }
...@@ -527,7 +558,8 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -527,7 +558,8 @@ public class PlaceBean implements PlaceBeanLocal {
PDF pdf = new PDF(outputStream); PDF pdf = new PDF(outputStream);
pdf.setTitle("Place"); 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 pagex = width / pointInMillim;
float pagey = height / pointInMillim; float pagey = height / pointInMillim;
...@@ -546,7 +578,7 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -546,7 +578,7 @@ public class PlaceBean implements PlaceBeanLocal {
double currentX = 42; double currentX = 42;
// nick // nick
if (place.getPlaceReserver() != null && place.getPlaceReserver().getUser() != null) { if (place.getPlaceReserver() != null && place.getPlaceReserver().getUser() != null) {
font = new com.pdfjet.Font(pdf, CoreFont.HELVETICA); font = new com.pdfjet.Font(pdf, CoreFont.HELVETICA);
font.setSize(font2); font.setSize(font2);
...@@ -558,12 +590,12 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -558,12 +590,12 @@ public class PlaceBean implements PlaceBeanLocal {
textLine.drawOn(page); textLine.drawOn(page);
} }
// place hex code // place hex code
font = new com.pdfjet.Font(pdf, CoreFont.HELVETICA); font = new com.pdfjet.Font(pdf, CoreFont.HELVETICA);
font.setSize(font2); font.setSize(font2);
textLine = new TextLine(font); textLine = new TextLine(font);
textLine.setText(barcodeBean.getPlaceHexcode(place)); textLine.setText(barcodeBean.getPlaceTextCode(place));
textLine.setPosition(currentX, (pagey / 2) + font1); textLine.setPosition(currentX, (pagey / 2) + font1);
textLine.setColor(new int[] { 0, 0, 0 }); textLine.setColor(new int[] { 0, 0, 0 });
textLine.drawOn(page); textLine.drawOn(page);
...@@ -586,4 +618,5 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -586,4 +618,5 @@ public class PlaceBean implements PlaceBeanLocal {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
} }
...@@ -34,20 +34,19 @@ import fi.codecrew.moya.model.LanEventPropertyKey; ...@@ -34,20 +34,19 @@ import fi.codecrew.moya.model.LanEventPropertyKey;
import fi.codecrew.moya.model.PlaceGroup; import fi.codecrew.moya.model.PlaceGroup;
import fi.codecrew.moya.model.User; import fi.codecrew.moya.model.User;
import fi.codecrew.moya.utilities.BarcodeUtils; import fi.codecrew.moya.utilities.BarcodeUtils;
import fi.codecrew.moya.utilities.I18n;
/** /**
* Session Bean implementation class PlaceGroupBean * Session Bean implementation class PlaceGroupBean
*/ */
@Stateless @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 { public class PlaceGroupBean implements PlaceGroupBeanLocal {
private static final Logger logger = LoggerFactory.getLogger(PlaceGroupBean.class); private static final Logger logger = LoggerFactory.getLogger(PlaceGroupBean.class);
private static final int YSTART = 30; private static final int YSTART = 30;
@EJB @EJB
private EventBeanLocal eventbean; private EventBeanLocal eventbean;
@EJB @EJB
private BarcodeBeanLocal barcodeBean; private BarcodeBeanLocal barcodeBean;
...@@ -87,7 +86,7 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal { ...@@ -87,7 +86,7 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
// } // }
@Override @Override
@RolesAllowed(SpecialPermission.S_USER) @RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public List<GroupMembership> getMembershipsAndCreations(EventUser user) { public List<GroupMembership> getMembershipsAndCreations(EventUser user) {
if (user == null) { if (user == null) {
user = permbean.getCurrentUser(); user = permbean.getCurrentUser();
...@@ -99,7 +98,7 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal { ...@@ -99,7 +98,7 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
} }
@Override @Override
@RolesAllowed(SpecialPermission.S_USER) @RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public List<GroupMembership> getMemberships(EventUser user) { public List<GroupMembership> getMemberships(EventUser user) {
if (user == null) { if (user == null) {
user = permbean.getCurrentUser(); user = permbean.getCurrentUser();
...@@ -133,59 +132,57 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal { ...@@ -133,59 +132,57 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
} }
@Override @Override
@RolesAllowed(SpecialPermission.S_USER) @RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public void getGroupMembershipPdf(EventUser usr, OutputStream ostream) { public void getGroupMembershipPdf(EventUser usr, OutputStream ostream) {
List<GroupMembership> memberships = getMembershipsAndCreations(usr); List<GroupMembership> memberships = getMembershipsAndCreations(usr);
LanEventProperty tmpProperty = eventbean.getProperty(LanEventPropertyKey.PLACECODE_FROM_USER); LanEventProperty tmpProperty = eventbean.getProperty(LanEventPropertyKey.PLACECODE_FROM_USER);
boolean placecodeFromUser = false; boolean placecodeFromUser = false;
if (tmpProperty != null && tmpProperty.isBooleanValue()) if (tmpProperty != null && tmpProperty.isBooleanValue())
{ {
placecodeFromUser = true; placecodeFromUser = true;
} }
tmpProperty = eventbean.getProperty(LanEventPropertyKey.PLACECODE_PRINT_ONLY_OWN); tmpProperty = eventbean.getProperty(LanEventPropertyKey.PLACECODE_PRINT_ONLY_OWN);
boolean printOnlyOwn = false; boolean printOnlyOwn = false;
if (tmpProperty != null && tmpProperty.isBooleanValue()) if (tmpProperty != null && tmpProperty.isBooleanValue())
{ {
printOnlyOwn = true; printOnlyOwn = true;
} }
try { try {
PDF pdf = new PDF(ostream); PDF pdf = new PDF(ostream);
Font font = new Font(pdf, CoreFont.TIMES_ROMAN); Font font = new Font(pdf, CoreFont.TIMES_ROMAN);
Font bigfont = new Font(pdf, CoreFont.TIMES_ROMAN); Font bigfont = new Font(pdf, CoreFont.TIMES_ROMAN);
bigfont.setSize(15); bigfont.setSize(15);
Font titlefont = new Font(pdf, CoreFont.TIMES_ROMAN); Font titlefont = new Font(pdf, CoreFont.TIMES_ROMAN);
titlefont.setSize(20); titlefont.setSize(20);
Page page = new Page(pdf, A4.PORTRAIT); Page page = new Page(pdf, A4.PORTRAIT);
int y = YSTART; int y = YSTART;
String titletext = "Lipputositteet"; String titletext = "Lipputositteet";
if(printOnlyOwn || memberships.size() <= 1) { if (printOnlyOwn || memberships.size() <= 1) {
titletext = "Lipputosite"; titletext = "Lipputosite";
} }
TextLine topic = new TextLine(titlefont, titletext); TextLine topic = new TextLine(titlefont, titletext);
topic.setPosition(230, y); topic.setPosition(230, y);
topic.drawOn(page); topic.drawOn(page);
y += 30; y += 30;
for (GroupMembership membership : memberships) { for (GroupMembership membership : memberships) {
if (y > 750) { if (y > 750) {
page = new Page(pdf, A4.PORTRAIT); page = new Page(pdf, A4.PORTRAIT);
y = YSTART; y = YSTART;
} }
if(printOnlyOwn && (membership.getUser() == null || !membership.getUser().equals(usr))) { if (printOnlyOwn && (membership.getUser() == null || !membership.getUser().equals(usr))) {
continue; continue;
} }
...@@ -194,16 +191,16 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal { ...@@ -194,16 +191,16 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
// PNGImage(BarcodeBean.getBarcode(membership.getInviteToken())); // PNGImage(BarcodeBean.getBarcode(membership.getInviteToken()));
// logger.debug("Jpeg: " + jpeg.getWidth() + " h. " + // logger.debug("Jpeg: " + jpeg.getWidth() + " h. " +
// jpeg.getHeight()); // jpeg.getHeight());
if(placecodeFromUser) { if (placecodeFromUser) {
if(membership.getUser() != null) { if (membership.getUser() != null) {
Image image = new Image(pdf, barcodeBean.getUserBarcode(membership.getUser()), ImageType.PNG); Image image = new Image(pdf, barcodeBean.getUserBarcode(membership.getUser()), ImageType.PNG);
image.scaleBy(0.8); image.scaleBy(0.8);
image.setPosition(50, y); image.setPosition(50, y);
image.drawOn(page); image.drawOn(page);
} else { } else {
TextLine nouser = new TextLine(bigfont, "EMPTY PLACE" ); TextLine nouser = new TextLine(bigfont, "EMPTY PLACE");
nouser.setPosition(85, y+10); nouser.setPosition(85, y + 10);
nouser.drawOn(page); nouser.drawOn(page);
} }
} else { } else {
...@@ -212,8 +209,6 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal { ...@@ -212,8 +209,6 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
image.setPosition(50, y); image.setPosition(50, y);
image.drawOn(page); image.drawOn(page);
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (membership.getPlaceReservation().getName() != null) if (membership.getPlaceReservation().getName() != null)
...@@ -246,24 +241,22 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal { ...@@ -246,24 +241,22 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
y += 130; y += 130;
} }
if (y > 750) { if (y > 750) {
page = new Page(pdf, A4.PORTRAIT); page = new Page(pdf, A4.PORTRAIT);
y = YSTART; y = YSTART;
} }
String footertext = "Nämä lipputositteenne tulee olla tulostettuna paperille kun saavutte tapahtumaan."; 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."; footertext = "Tämä henkilökohtainen lipputositteesi tulee olla mukana tulostettuna paperille kun saavut tapahtumaan.";
} }
TextLine footer = new TextLine(font, footertext); TextLine footer = new TextLine(font, footertext);
footer.setPosition(50, y); footer.setPosition(50, y);
footer.drawOn(page); footer.drawOn(page);
pdf.flush(); pdf.flush();
} catch (Exception e) { } catch (Exception e) {
logger.info("Error getting printing group memberships", e); logger.info("Error getting printing group memberships", e);
...@@ -272,19 +265,20 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal { ...@@ -272,19 +265,20 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
} }
@Override @Override
@RolesAllowed(SpecialPermission.S_USER) @RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public void releaseAndGenerateToken(GroupMembership gmem) { 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))) { 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); loggerbean.logMessage(SecurityLogType.permissionDenied, permbean.getCurrentUser(), "User tried to release and generate group membership: " + gmem);
throw new EJBAccessException("Not enough rights to release token"); throw new EJBAccessException("Not enough rights to release token");
} }
gmem.setUser(null); gmem.setUser(null);
gmem.setInviteToken(gmemfacade.createInviteToken()); gmem.setInviteToken(gmemfacade.createInviteToken());
logger.info("Place released. {} new token {}", gmem.getInviteToken());
} }
@Override @Override
@RolesAllowed(SpecialPermission.S_USER) @RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public List<PlaceGroup> getPlacegroups(EventUser user) { public List<PlaceGroup> getPlacegroups(EventUser user) {
return pgfacade.find(user); return pgfacade.find(user);
} }
...@@ -299,6 +293,6 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal { ...@@ -299,6 +293,6 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
public void markGrouMembershipNotEntered(GroupMembership membership) { public void markGrouMembershipNotEntered(GroupMembership membership) {
membership.setEnteredEvent(null); membership.setEnteredEvent(null);
membership = gmemfacade.merge(membership); membership = gmemfacade.merge(membership);
} }
} }
...@@ -104,6 +104,9 @@ public class ProductBean implements ProductBeanLocal { ...@@ -104,6 +104,9 @@ public class ProductBean implements ProductBeanLocal {
@EJB @EJB
private DiscountBean discountBean; private DiscountBean discountBean;
@EJB
private CardTemplateBean cardTemplateBean;
private static final Logger logger = LoggerFactory.getLogger(ProductBean.class); private static final Logger logger = LoggerFactory.getLogger(ProductBean.class);
/** /**
...@@ -350,6 +353,7 @@ public class ProductBean implements ProductBeanLocal { ...@@ -350,6 +353,7 @@ public class ProductBean implements ProductBeanLocal {
public AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user) { public AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user) {
user = eventUserFacade.reload(user); user = eventUserFacade.reload(user);
AccountEvent ret = productPBean.createAccountEvent(product, quantity, user, Calendar.getInstance()); AccountEvent ret = productPBean.createAccountEvent(product, quantity, user, Calendar.getInstance());
cardTemplateBean.checkPrintedCard(user);
return ret; return ret;
} }
......
...@@ -30,7 +30,7 @@ public class ProductPBean { ...@@ -30,7 +30,7 @@ public class ProductPBean {
@EJB @EJB
private PermissionBean permbean; private PermissionBean permbean;
@EJB @EJB
private DiscountBean discountBean; private DiscountBean discountBean;
@EJB @EJB
...@@ -100,10 +100,8 @@ public class ProductPBean { ...@@ -100,10 +100,8 @@ public class ProductPBean {
// discountinstancefacade.create(discInst); // discountinstancefacade.create(discInst);
accEventdiscounts.add(new DiscountInstance(ret, d)); accEventdiscounts.add(new DiscountInstance(ret, d));
} }
if (user.getAccountEvents() == null) {
user.setAccountEvents(new ArrayList<AccountEvent>()); user.addAccountevent(ret);
}
user.getAccountEvents().add(ret);
accounteventfacade.create(ret); accounteventfacade.create(ret);
logger.debug("create ac {} for user {}", ret, user.getUser()); logger.debug("create ac {} for user {}", ret, user.getUser());
// flush changes to db. // 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; ...@@ -21,6 +21,7 @@ import org.slf4j.LoggerFactory;
import fi.codecrew.moya.enums.apps.IAppPermission; import fi.codecrew.moya.enums.apps.IAppPermission;
import fi.codecrew.moya.enums.apps.UserPermission; import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.facade.RoleFacade; import fi.codecrew.moya.facade.RoleFacade;
import fi.codecrew.moya.facade.UserFacade; import fi.codecrew.moya.facade.UserFacade;
import fi.codecrew.moya.model.ApplicationPermission; import fi.codecrew.moya.model.ApplicationPermission;
...@@ -51,6 +52,15 @@ public class RoleBean implements RoleBeanLocal { ...@@ -51,6 +52,15 @@ public class RoleBean implements RoleBeanLocal {
@EJB @EJB
private UserFacade userFacade; private UserFacade userFacade;
@EJB
private EventUserFacade eventuserfacade;
@EJB
private EventBeanLocal permbean;
@EJB
private CardTemplateBean cardTemplateBean;
// VIEW_ALL pitää olla että voidaan hakea roolien perusteella. // VIEW_ALL pitää olla että voidaan hakea roolien perusteella.
@Override @Override
@RolesAllowed({ UserPermission.S_READ_ROLES, UserPermission.S_VIEW_ALL }) @RolesAllowed({ UserPermission.S_READ_ROLES, UserPermission.S_VIEW_ALL })
...@@ -161,6 +171,28 @@ public class RoleBean implements RoleBeanLocal { ...@@ -161,6 +171,28 @@ public class RoleBean implements RoleBeanLocal {
return role; 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 @Override
@RolesAllowed(UserPermission.S_WRITE_ROLES) @RolesAllowed(UserPermission.S_WRITE_ROLES)
public void saveRoles(EventUser usr, List<Role> usersRoles) { public void saveRoles(EventUser usr, List<Role> usersRoles) {
...@@ -176,6 +208,8 @@ public class RoleBean implements RoleBeanLocal { ...@@ -176,6 +208,8 @@ public class RoleBean implements RoleBeanLocal {
ur.getUsers().remove(usr); ur.getUsers().remove(usr);
} }
} }
cardTemplateBean.checkPrintedCard(usr);
} }
@Override @Override
......
...@@ -59,6 +59,7 @@ public class VotingBean implements VotingBeanLocal { ...@@ -59,6 +59,7 @@ public class VotingBean implements VotingBeanLocal {
voteFacade.create(v); voteFacade.create(v);
} }
@RolesAllowed(CompoPermission.S_MANAGE)
public void createCompo(Compo c) { public void createCompo(Compo c) {
c.setEvent(eventBean.getCurrentEvent()); c.setEvent(eventBean.getCurrentEvent());
compoFacade.create(c); compoFacade.create(c);
...@@ -73,15 +74,15 @@ public class VotingBean implements VotingBeanLocal { ...@@ -73,15 +74,15 @@ public class VotingBean implements VotingBeanLocal {
c.getCompoEntries().add(compoEntry); c.getCompoEntries().add(compoEntry);
compoFacade.flush(); compoFacade.flush();
compoEntryFile.setEntriesId(compoEntry); compoEntryFile.setEntriesId(compoEntry);
compoEntry.getFiles().add(compoEntryFile); // compoEntry.getFiles().add(compoEntryFile);
} }
public Compo getCompoById(Integer compoId) { public Compo getCompoById(Integer compoId) {
return compoFacade.find(compoId); return compoFacade.find(compoId);
} }
public List<Compo> getCompoList() { public List<Compo> getCompoList(boolean showHidden) {
return compoFacade.getList(); return compoFacade.getList(showHidden);
} }
@Override @Override
...@@ -129,16 +130,17 @@ public class VotingBean implements VotingBeanLocal { ...@@ -129,16 +130,17 @@ public class VotingBean implements VotingBeanLocal {
return compoEntryFacade.find(entryId); return compoEntryFacade.find(entryId);
} }
@Override // @Override
public CompoEntry findEntryWithFiles(Integer entryId) { // public CompoEntry findEntryWithFiles(Integer entryId) {
CompoEntry ret = compoEntryFacade.find(entryId); // CompoEntry ret = compoEntryFacade.find(entryId);
logger.debug("Found files {}", ret.getFiles().size()); // // logger.debug("Found files {}", ret.getFiles().size());
//
return ret; // return ret;
//
} // }
@Override @Override
@RolesAllowed(CompoPermission.S_MANAGE)
public CompoEntry saveSort(CompoEntry e) { public CompoEntry saveSort(CompoEntry e) {
CompoEntry entry = compoEntryFacade.find(e.getId()); CompoEntry entry = compoEntryFacade.find(e.getId());
entry.setSort(e.getSort()); entry.setSort(e.getSort());
...@@ -177,4 +179,15 @@ public class VotingBean implements VotingBeanLocal { ...@@ -177,4 +179,15 @@ public class VotingBean implements VotingBeanLocal {
return voteEntity; 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; ...@@ -3,14 +3,14 @@ package fi.codecrew.moya.facade;
import javax.ejb.LocalBean; import javax.ejb.LocalBean;
import javax.ejb.Stateless; import javax.ejb.Stateless;
import fi.codecrew.moya.model.CardBarcode; import fi.codecrew.moya.model.CardCode;
@Stateless @Stateless
@LocalBean @LocalBean
public class CardBarcodeFacade extends IntegerPkGenericFacade<CardBarcode> { public class CardCodeFacade extends IntegerPkGenericFacade<CardCode> {
public CardBarcodeFacade() { public CardCodeFacade() {
super(CardBarcode.class); super(CardCode.class);
} }
} }
package fi.codecrew.moya.facade; package fi.codecrew.moya.facade;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
...@@ -7,11 +8,12 @@ import javax.ejb.LocalBean; ...@@ -7,11 +8,12 @@ import javax.ejb.LocalBean;
import javax.ejb.Stateless; import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.Compo_;
import fi.codecrew.moya.beans.EventBeanLocal; import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.Compo; import fi.codecrew.moya.model.Compo;
import fi.codecrew.moya.model.Compo_;
@Stateless @Stateless
@LocalBean @LocalBean
...@@ -23,11 +25,17 @@ public class CompoFacade extends IntegerPkGenericFacade<Compo> { ...@@ -23,11 +25,17 @@ public class CompoFacade extends IntegerPkGenericFacade<Compo> {
super(Compo.class); super(Compo.class);
} }
public List<Compo> getList() { public List<Compo> getList(boolean showHidden) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<Compo> cq = cb.createQuery(Compo.class); CriteriaQuery<Compo> cq = cb.createQuery(Compo.class);
Root<Compo> root = cq.from(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))); cq.orderBy(cb.desc(root.get(Compo_.startTime)));
List<Compo> ret = getEm().createQuery(cq).getResultList(); List<Compo> ret = getEm().createQuery(cq).getResultList();
return ret; return ret;
......
...@@ -13,15 +13,21 @@ import javax.persistence.criteria.CriteriaBuilder; ...@@ -13,15 +13,21 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From; import javax.persistence.criteria.From;
import javax.persistence.criteria.Root; 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.beans.EventBeanLocal;
import fi.codecrew.moya.enums.DatabaseHasCompare; import fi.codecrew.moya.enums.DatabaseHasCompare;
import fi.codecrew.moya.enums.DatabaseValueCompare; import fi.codecrew.moya.enums.DatabaseValueCompare;
import fi.codecrew.moya.facade.callbacks.EventLimiter; import fi.codecrew.moya.facade.callbacks.EventLimiter;
import fi.codecrew.moya.facade.callbacks.EventUserAccountSaldoPredicate; 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.EventUserPlacegroupPredicate;
import fi.codecrew.moya.facade.callbacks.EventUserRolefilter; import fi.codecrew.moya.facade.callbacks.EventUserRolefilter;
import fi.codecrew.moya.facade.callbacks.EventUserSearchPredicate; 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.facade.callbacks.OrderCallback;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_; import fi.codecrew.moya.model.EventUser_;
...@@ -29,6 +35,7 @@ import fi.codecrew.moya.model.LanEvent; ...@@ -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.model.User_; import fi.codecrew.moya.model.User_;
import fi.codecrew.moya.util.UserSearchQuery; import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.jpa.FacadeCallback; import fi.codecrew.moya.utilities.jpa.FacadeCallback;
...@@ -47,6 +54,7 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> { ...@@ -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 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) { public EventUser findByLogin(final String login) {
LanEvent event = eventBean.getCurrentEvent(); LanEvent event = eventBean.getCurrentEvent();
...@@ -82,10 +90,13 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> { ...@@ -82,10 +90,13 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
} }
public EventUser find(User user) { public EventUser find(User user) {
LanEvent event = eventBean.getCurrentEvent(); return getOtherOrganisationsEventuser(user, eventBean.getCurrentEvent());
EventUser ret; }
if ((ret = checkCache(user.getLogin(), event)) == null)
{ public EventUser getOtherOrganisationsEventuser(User user, LanEvent event)
{
EventUser ret = null;
if ((ret = checkCache(user.getLogin(), event)) == null) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<EventUser> cq = cb.createQuery(EventUser.class); CriteriaQuery<EventUser> cq = cb.createQuery(EventUser.class);
Root<EventUser> root = cq.from(EventUser.class); Root<EventUser> root = cq.from(EventUser.class);
...@@ -108,19 +119,40 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> { ...@@ -108,19 +119,40 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
public SearchResult<EventUser> searchEventUsers(UserSearchQuery query) { public SearchResult<EventUser> searchEventUsers(UserSearchQuery query) {
ArrayList<FacadeCallback<EventUser>> callbacks = new ArrayList<FacadeCallback<EventUser>>(); ArrayList<FacadeCallback<EventUser>> callbacks = new ArrayList<FacadeCallback<EventUser>>();
callbacks.add(new OrderCallback<EventUser>(false, EventUser_.id)); CriteriaBuilder cb = getEm().getCriteriaBuilder();
callbacks.add(new EventLimiter(eventBean.getCurrentEvent()));
if (query.getSearch() != null && !query.getSearch().isEmpty()) 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())); callbacks.add(new EventUserSearchPredicate(query.getSearch(), UserFacade.getAttrlist()));
} }
if (query.isPlaceAssoc()) if (query.isPlaceAssoc()) {
{
callbacks.add(new EventUserPlacegroupPredicate()); callbacks.add(new EventUserPlacegroupPredicate());
} }
if (query.getFilterRoles() != null && !query.getFilterRoles().isEmpty()) { if (query.getFilterRoles() != null && !query.getFilterRoles().isEmpty()) {
callbacks.add(new EventUserRolefilter(query.getFilterRoles())); callbacks.add(new EventUserRolefilter(query.getFilterRoles()));
} }
if (query.getHasCardState() != null && !query.getHasCardState().isEmpty()) {
callbacks.add(new EventUserCardStateFilter(query.getHasCardState()));
}
if (query.getAccountSaldo() != null && if (query.getAccountSaldo() != null &&
query.getAccountSaldoCompare() != null && query.getAccountSaldoCompare() != null &&
!DatabaseValueCompare.NONE.equals(query.getAccountSaldoCompare())) !DatabaseValueCompare.NONE.equals(query.getAccountSaldoCompare()))
...@@ -132,11 +164,6 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> { ...@@ -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> listRoot = searchCallbacks(listCQuery, callbacks, EventUser.class);
From<?, EventUser> countRoot = searchCallbacks(countCQuery, callbacks, EventUser.class); From<?, EventUser> countRoot = searchCallbacks(countCQuery, callbacks, EventUser.class);
......
...@@ -9,10 +9,10 @@ import javax.persistence.criteria.CriteriaBuilder; ...@@ -9,10 +9,10 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.OrgRole_;
import fi.codecrew.moya.beans.EventBeanLocal; import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.EventOrganiser; import fi.codecrew.moya.model.EventOrganiser;
import fi.codecrew.moya.model.OrgRole; import fi.codecrew.moya.model.OrgRole;
import fi.codecrew.moya.model.OrgRole_;
import fi.codecrew.moya.model.User; import fi.codecrew.moya.model.User;
/** /**
...@@ -29,17 +29,19 @@ public class OrgRoleFacade extends IntegerPkGenericFacade<OrgRole> { ...@@ -29,17 +29,19 @@ public class OrgRoleFacade extends IntegerPkGenericFacade<OrgRole> {
super(OrgRole.class); super(OrgRole.class);
} }
public List<OrgRole> findForUser(User user) { public List<OrgRole> findForUser(User user, EventOrganiser organisation) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<OrgRole> cq = cb.createQuery(OrgRole.class); CriteriaQuery<OrgRole> cq = cb.createQuery(OrgRole.class);
Root<OrgRole> root = cq.from(OrgRole.class); Root<OrgRole> root = cq.from(OrgRole.class);
cq.where(cb.equal(root.get(OrgRole_.eventOrganisation), eventBean cq.where(cb.equal(root.get(OrgRole_.eventOrganisation), organisation), cb.isMember(user, root.get(OrgRole_.users)));
.getCurrentEvent().getOrganiser()), cb.isMember(user,
root.get(OrgRole_.users)));
return getEm().createQuery(cq).getResultList(); return getEm().createQuery(cq).getResultList();
} }
public List<OrgRole> findForUser(User user) {
return findForUser(user, eventBean.getCurrentEvent().getOrganiser());
}
public OrgRole createRole(EventOrganiser org, String roleName) { public OrgRole createRole(EventOrganiser org, String roleName) {
OrgRole ret = new OrgRole(); OrgRole ret = new OrgRole();
ret.setEventOrganisation(org); ret.setEventOrganisation(org);
......
...@@ -3,7 +3,6 @@ package fi.codecrew.moya.facade; ...@@ -3,7 +3,6 @@ package fi.codecrew.moya.facade;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
...@@ -14,9 +13,12 @@ import javax.persistence.criteria.CriteriaBuilder; ...@@ -14,9 +13,12 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import fi.codecrew.moya.beans.EventBeanLocal; import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.enums.CardState; 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.CardTemplate_;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEvent; import fi.codecrew.moya.model.LanEvent;
...@@ -35,31 +37,19 @@ public class PrintedCardFacade extends IntegerPkGenericFacade<PrintedCard> { ...@@ -35,31 +37,19 @@ public class PrintedCardFacade extends IntegerPkGenericFacade<PrintedCard> {
@EJB @EJB
private EventBeanLocal eventbean; private EventBeanLocal eventbean;
public PrintedCard findByRfid(String uid) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); public PrintedCard findByCode(String code) {
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) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<PrintedCard> cq = cb.createQuery(PrintedCard.class); CriteriaQuery<CardCode> cq = cb.createQuery(CardCode.class);
Root<PrintedCard> root = cq.from(PrintedCard.class); Root<CardCode> root = cq.from(CardCode.class);
cq.where(cb.equal(root.get(PrintedCard_.barcode), barcode), cq.where(cb.equal(root.get(CardCode_.code), code),
cb.equal(root.get(PrintedCard_.event), eventbean.getCurrentEvent())); 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) { public List<PrintedCard> findAllEnabled(LanEvent currentEvent) {
...@@ -85,14 +75,16 @@ public class PrintedCardFacade extends IntegerPkGenericFacade<PrintedCard> { ...@@ -85,14 +75,16 @@ public class PrintedCardFacade extends IntegerPkGenericFacade<PrintedCard> {
} }
public PrintedCard findLatestByRfidFromAny(String uid) { public PrintedCard findLatestByCodeFromAny(String code) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<PrintedCard> cq = cb.createQuery(PrintedCard.class); CriteriaQuery<PrintedCard> cq = cb.createQuery(PrintedCard.class);
Root<PrintedCard> root = cq.from(PrintedCard.class); Root<CardCode> root = cq.from(CardCode.class);
cq.select(root.get(CardCode_.printedCard));
cq.where(cb.equal(root.get(PrintedCard_.rfidUid), uid));
cq.orderBy(cb.desc(root.get(PrintedCard_.printTime))); 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); TypedQuery<PrintedCard> q = getEm().createQuery(cq);
q.setMaxResults(1); q.setMaxResults(1);
......
...@@ -11,10 +11,11 @@ import javax.persistence.criteria.CriteriaBuilder; ...@@ -11,10 +11,11 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.Product_;
import fi.codecrew.moya.beans.EventBeanLocal; import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.Product; import fi.codecrew.moya.model.Product;
import fi.codecrew.moya.model.ProductFlag; import fi.codecrew.moya.model.ProductFlag;
import fi.codecrew.moya.model.Product_;
@Stateless @Stateless
@LocalBean @LocalBean
...@@ -44,11 +45,15 @@ public class ProductFacade extends IntegerPkGenericFacade<Product> { ...@@ -44,11 +45,15 @@ public class ProductFacade extends IntegerPkGenericFacade<Product> {
} }
public List<Product> findProductsByPrice(BigDecimal price) { public List<Product> findProductsByPrice(BigDecimal price) {
return findProductsByPrice(price, eventbean.getCurrentEvent());
}
public List<Product> findProductsByPrice(BigDecimal price, LanEvent event) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class); CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> root = cq.from(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)); cb.equal(root.get(Product_.price), price));
return getEm().createQuery(cq).getResultList(); return getEm().createQuery(cq).getResultList();
...@@ -65,18 +70,19 @@ public class ProductFacade extends IntegerPkGenericFacade<Product> { ...@@ -65,18 +70,19 @@ public class ProductFacade extends IntegerPkGenericFacade<Product> {
return getEm().createQuery(cq).getResultList(); return getEm().createQuery(cq).getResultList();
} }
public Product findProductByBarcode(String barcode) { public Product findProductByBarcode(String barcode) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class); CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> root = cq.from(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) cb.equal(root.get(Product_.barcode), barcode)
); );
return super.getSingleNullableResult(getEm().createQuery(cq)); return super.getSingleNullableResult(getEm().createQuery(cq));
} }
} }
...@@ -31,8 +31,26 @@ public class ReaderEventFacade extends IntegerPkGenericFacade<ReaderEvent> { ...@@ -31,8 +31,26 @@ public class ReaderEventFacade extends IntegerPkGenericFacade<ReaderEvent> {
cq.orderBy(cb.desc(root.get(ReaderEvent_.time))); cq.orderBy(cb.desc(root.get(ReaderEvent_.time)));
TypedQuery<ReaderEvent> q = getEm().createQuery(cq); TypedQuery<ReaderEvent> q = getEm().createQuery(cq);
q.setMaxResults(count); if (count > 0) {
q.setMaxResults(count);
}
return q.getResultList(); 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; ...@@ -15,12 +15,13 @@ import javax.persistence.metamodel.SingularAttribute;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.facade.callbacks.OrderCallback; import fi.codecrew.moya.facade.callbacks.OrderCallback;
import fi.codecrew.moya.facade.callbacks.StringSearchPredicateCreator; 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.model.User_;
import fi.codecrew.moya.utilities.SearchQuery; import fi.codecrew.moya.utilities.SearchQuery;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
import fi.codecrew.moya.utilities.SearchResult; import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.jpa.FacadeCallback; import fi.codecrew.moya.utilities.jpa.FacadeCallback;
...@@ -102,11 +103,11 @@ public class UserFacade extends IntegerPkGenericFacade<User> { ...@@ -102,11 +103,11 @@ public class UserFacade extends IntegerPkGenericFacade<User> {
public SearchResult<User> searchAllUsers(SearchQuery search) { public SearchResult<User> searchAllUsers(SearchQuery search) {
List<FacadeCallback<User>> callbacks = new ArrayList<FacadeCallback<User>>(); List<FacadeCallback<User>> callbacks = new ArrayList<FacadeCallback<User>>();
if (search.getSort() == null || search.getSort().isEmpty()) {
callbacks.add(new OrderCallback<User>(false, User_.id)); // Ascending if null or not descending..
} else { boolean asc = search.getSortDirection() == null || !QuerySortOrder.DESCENDING.equals(search.getSortDirection());
callbacks.add(new OrderCallback<User>(false, search.getSort())); SingularAttribute<? super User, ?> sortfield = getUserField(search.getSort());
} callbacks.add(new OrderCallback<User>(asc, sortfield));
callbacks.add(new StringSearchPredicateCreator<User>(search.getSearch(), getAttrlist())); callbacks.add(new StringSearchPredicateCreator<User>(search.getSearch(), getAttrlist()));
return super.searcher(search, callbacks); return super.searcher(search, callbacks);
...@@ -142,6 +143,68 @@ public class UserFacade extends IntegerPkGenericFacade<User> { ...@@ -142,6 +143,68 @@ public class UserFacade extends IntegerPkGenericFacade<User> {
return getEm().createQuery(cq).getResultList(); 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) // public SearchResult<User> searchEventUsers(SearchQuery query)
// { // {
// ArrayList<FacadeCallback<EventUser>> callbacks = new // ArrayList<FacadeCallback<EventUser>> callbacks = new
......
...@@ -5,7 +5,7 @@ import java.util.List; ...@@ -5,7 +5,7 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From; import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.SingularAttribute;
...@@ -27,7 +27,7 @@ public class AndPredicateCreator<A, T extends ModelInterface> implements FacadeC ...@@ -27,7 +27,7 @@ public class AndPredicateCreator<A, T extends ModelInterface> implements FacadeC
} }
@Override @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()) { if (searchval == null || attributes == null || attributes.isEmpty()) {
return; return;
} }
......
...@@ -4,11 +4,11 @@ import java.util.List; ...@@ -4,11 +4,11 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From; import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate; 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.EventUser_;
import fi.codecrew.moya.model.LanEvent; import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.utilities.jpa.FacadeCallback; import fi.codecrew.moya.utilities.jpa.FacadeCallback;
...@@ -21,7 +21,7 @@ public class EventLimiter implements FacadeCallback<EventUser> { ...@@ -21,7 +21,7 @@ public class EventLimiter implements FacadeCallback<EventUser> {
} }
@Override @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)); predicates.add(cb.equal(root.get(EventUser_.event), ev));
} }
......
...@@ -5,14 +5,14 @@ import java.util.List; ...@@ -5,14 +5,14 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From; import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery; import javax.persistence.criteria.Subquery;
import fi.codecrew.moya.model.AccountEvent_;
import fi.codecrew.moya.enums.DatabaseValueCompare; import fi.codecrew.moya.enums.DatabaseValueCompare;
import fi.codecrew.moya.model.AccountEvent; import fi.codecrew.moya.model.AccountEvent;
import fi.codecrew.moya.model.AccountEvent_;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.utilities.jpa.FacadeCallback; import fi.codecrew.moya.utilities.jpa.FacadeCallback;
...@@ -27,7 +27,7 @@ public class EventUserAccountSaldoPredicate implements FacadeCallback<EventUser> ...@@ -27,7 +27,7 @@ public class EventUserAccountSaldoPredicate implements FacadeCallback<EventUser>
} }
@Override @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); Subquery<BigDecimal> subq = cq.subquery(BigDecimal.class);
Root<AccountEvent> acRoot = subq.from(AccountEvent.class); Root<AccountEvent> acRoot = subq.from(AccountEvent.class);
subq.where(cb.equal(acRoot.get(AccountEvent_.user), root)); 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; ...@@ -4,17 +4,17 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From; import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate; 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.EventUser_;
import fi.codecrew.moya.utilities.jpa.FacadeCallback; import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventUserPlacegroupPredicate implements FacadeCallback<EventUser> { public class EventUserPlacegroupPredicate implements FacadeCallback<EventUser> {
@Override @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))); predicates.add(cb.isNotEmpty(root.get(EventUser_.groupMemberships)));
} }
......
...@@ -8,7 +8,6 @@ import java.util.Set; ...@@ -8,7 +8,6 @@ import java.util.Set;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path; import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
...@@ -18,13 +17,13 @@ import org.slf4j.Logger; ...@@ -18,13 +17,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import fi.codecrew.moya.model.AccountEvent_; import fi.codecrew.moya.model.AccountEvent_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_; import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.GroupMembership_; import fi.codecrew.moya.model.GroupMembership_;
import fi.codecrew.moya.model.Place_; import fi.codecrew.moya.model.Place_;
import fi.codecrew.moya.model.Product_; 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.model.Role_;
import fi.codecrew.moya.utilities.jpa.FacadeCallback; import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventUserRolefilter implements FacadeCallback<EventUser> { public class EventUserRolefilter implements FacadeCallback<EventUser> {
...@@ -49,7 +48,7 @@ public class EventUserRolefilter implements FacadeCallback<EventUser> { ...@@ -49,7 +48,7 @@ public class EventUserRolefilter implements FacadeCallback<EventUser> {
return checkedRoles; 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()) if (roles != null && !roles.isEmpty())
{ {
HashSet<Integer> roleids = new HashSet<Integer>(); 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; ...@@ -4,7 +4,7 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From; import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.SingularAttribute;
...@@ -25,7 +25,7 @@ public class OrPredicateCreator<A, T extends ModelInterface> implements FacadeCa ...@@ -25,7 +25,7 @@ public class OrPredicateCreator<A, T extends ModelInterface> implements FacadeCa
} }
@Override @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()) { if (searchstr == null || attributes == null || attributes.isEmpty()) {
return; return;
} }
......
...@@ -4,11 +4,14 @@ import java.util.List; ...@@ -4,11 +4,14 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From; import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Path; import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute; 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.FacadeCallback;
import fi.codecrew.moya.utilities.jpa.ModelInterface; import fi.codecrew.moya.utilities.jpa.ModelInterface;
...@@ -17,6 +20,7 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T ...@@ -17,6 +20,7 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T
private final SingularAttribute<? super T, ?> sort; private final SingularAttribute<? super T, ?> sort;
private final boolean asc; private final boolean asc;
private String sortstr; private String sortstr;
private static final Logger logger = LoggerFactory.getLogger(OrderCallback.class);
public OrderCallback(boolean asc, SingularAttribute<? super T, ?> sortAttr) { public OrderCallback(boolean asc, SingularAttribute<? super T, ?> sortAttr) {
sort = sortAttr; sort = sortAttr;
...@@ -31,16 +35,15 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T ...@@ -31,16 +35,15 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T
} }
@Override @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(); Class<?> rettype = cq.getResultType();
// Check if returntype is entity or are we for example counting results // Check if returntype is entity or are we for example counting results
if (!ModelInterface.class.isAssignableFrom(rettype)) if (!ModelInterface.class.isAssignableFrom(rettype)) {
{
return; return;
} }
Path<?> path = null; Expression<?> path = null;
if (sort == null) { if (sort == null) {
if (sortstr == null) { if (sortstr == null) {
return; return;
...@@ -56,6 +59,9 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T ...@@ -56,6 +59,9 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T
if (path == null) { if (path == null) {
return; return;
} }
if (path.getJavaType().equals(String.class)) {
path = cb.lower((Expression<String>) path);
}
if (asc) { if (asc) {
cq.orderBy(cb.asc(path)); cq.orderBy(cb.asc(path));
......
...@@ -5,7 +5,6 @@ import java.util.List; ...@@ -5,7 +5,6 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path; import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.SingularAttribute;
...@@ -44,7 +43,7 @@ public abstract class PathStringSearchPredicateCreator<T extends ModelInterface, ...@@ -44,7 +43,7 @@ public abstract class PathStringSearchPredicateCreator<T extends ModelInterface,
} }
@Override @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()) { if (searchstr == null || attributes == null || attributes.isEmpty()) {
return; return;
} }
......
...@@ -62,5 +62,11 @@ ...@@ -62,5 +62,11 @@
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>4.3-beta2</version> <version>4.3-beta2</version>
</dependency> </dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.5</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
</project> </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; ...@@ -8,6 +8,7 @@ import javax.ejb.Local;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Place; import fi.codecrew.moya.model.Place;
import fi.codecrew.moya.model.PrintedCard; import fi.codecrew.moya.model.PrintedCard;
import fi.codecrew.moya.model.Product;
@Local @Local
public interface BarcodeBeanLocal { public interface BarcodeBeanLocal {
...@@ -17,8 +18,11 @@ public interface BarcodeBeanLocal { ...@@ -17,8 +18,11 @@ public interface BarcodeBeanLocal {
public InputStream getUserBarcode(EventUser user) throws IOException; public InputStream getUserBarcode(EventUser user) throws IOException;
public InputStream getCardBarcode(PrintedCard printedCard) throws IOException; public InputStream getCardBarcode(PrintedCard printedCard) throws IOException;
public String getPlaceHexcode(Place place); public String getPlaceTextCode(Place place);
public Place getPlaceFromHexcode(String hexcode); public Place getPlaceFromTextCode(String hexcode);
public String checkVrAuthCode(String code); 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; ...@@ -9,6 +9,7 @@ import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.model.CardTemplate; import fi.codecrew.moya.model.CardTemplate;
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.model.ReaderEvent;
import fi.codecrew.moya.utilities.jsf.EntityFinderBean; import fi.codecrew.moya.utilities.jsf.EntityFinderBean;
@Local @Local
......
...@@ -35,7 +35,13 @@ public interface EventBeanLocal { ...@@ -35,7 +35,13 @@ public interface EventBeanLocal {
List<LanEventPrivateProperty> getPrivateProperties(); List<LanEventPrivateProperty> getPrivateProperties();
LanEventPrivateProperty saveOrCreatePrivateProperty(LanEventPrivateProperty privateProperty); LanEventPrivateProperty saveOrCreatePrivateProperty(LanEventPrivateProperty privateProperty);
long getPropertyLong(LanEventPropertyKey property); long getPropertyLong(LanEventPropertyKey property);
LanEvent getEventById(Integer id);
LanEvent deleteProperty(LanEventProperty property);
LanEvent deletePrivateProperty(LanEventPrivateProperty property);
} }
...@@ -24,4 +24,6 @@ public interface EventMapBeanLocal { ...@@ -24,4 +24,6 @@ public interface EventMapBeanLocal {
Place updatePlace(Place place); 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 { ...@@ -63,10 +63,13 @@ public interface PlaceBeanLocal {
*/ */
byte[] generatePlacesPdf(float width, float height, double font1, double font2); byte[] generatePlacesPdf(float width, float height, double font1, double font2);
// public byte[] generatePlacesPdf(double width, double height, double font1, double font2); // public byte[] generatePlacesPdf(double width, double height, double font1, double font2);
List<GroupMembership> matchGroupMembershipsByInviteToken(String token); List<GroupMembership> matchGroupMembershipsByInviteToken(String token);
GroupMembership findGroupMembershipsByToken(String token); GroupMembership findGroupMembershipsByToken(String token);
PlaceGroup reserveSelectedPlaces(EventUser eventuser) throws BortalCatchableException;
} }
...@@ -17,7 +17,7 @@ public interface ReaderBeanLocal { ...@@ -17,7 +17,7 @@ public interface ReaderBeanLocal {
// ReaderEvent assocTagToPlacecode(String tag, String readerIdent, String // ReaderEvent assocTagToPlacecode(String tag, String readerIdent, String
// placecode) throws BortalCatchableException, PermissionDeniedException; // placecode) throws BortalCatchableException, PermissionDeniedException;
ReaderEvent assocTagToCard(String tag, String readerIdent, PrintedCard card); ReaderEvent assocCodeToCard(ReaderEvent readerEvent, PrintedCard card);
List<Reader> getReaders(); List<Reader> getReaders();
...@@ -27,7 +27,8 @@ public interface ReaderBeanLocal { ...@@ -27,7 +27,8 @@ public interface ReaderBeanLocal {
User findTagFromAnyEvent(String value); 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); Reader getReader(Integer readerid);
...@@ -39,6 +40,12 @@ public interface ReaderBeanLocal { ...@@ -39,6 +40,12 @@ public interface ReaderBeanLocal {
List<ReaderEvent> getLastReaderEvents(); 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 { ...@@ -36,4 +36,6 @@ public interface RoleBeanLocal {
public List<Role> getRoles(EventUser selectedUser); public List<Role> getRoles(EventUser selectedUser);
Role addRole(EventUser eventuser, Role role);
} }
...@@ -2,6 +2,7 @@ package fi.codecrew.moya.beans; ...@@ -2,6 +2,7 @@ package fi.codecrew.moya.beans;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
...@@ -10,6 +11,7 @@ import fi.codecrew.moya.model.EventUser; ...@@ -10,6 +11,7 @@ import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Feedback; import fi.codecrew.moya.model.Feedback;
import fi.codecrew.moya.model.GameID; import fi.codecrew.moya.model.GameID;
import fi.codecrew.moya.model.GroupMembership; import fi.codecrew.moya.model.GroupMembership;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.Role; import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.model.TournamentGame; import fi.codecrew.moya.model.TournamentGame;
import fi.codecrew.moya.model.User; import fi.codecrew.moya.model.User;
...@@ -26,7 +28,7 @@ public interface UserBeanLocal { ...@@ -26,7 +28,7 @@ public interface UserBeanLocal {
SearchResult<User> getUsers(SearchQuery search); SearchResult<User> getUsers(SearchQuery search);
SearchResult<User> getEventUsers(SearchQuery search); //SearchResult<User> getEventUsers(SearchQuery search);
EventUser mergeChanges(EventUser user); EventUser mergeChanges(EventUser user);
...@@ -40,6 +42,8 @@ public interface UserBeanLocal { ...@@ -40,6 +42,8 @@ public interface UserBeanLocal {
boolean resetPassword(User user, String password, String hash); boolean resetPassword(User user, String password, String hash);
public User getUser(Integer id);
/** /**
* Search EventUser entity by User entity ID * Search EventUser entity by User entity ID
* *
...@@ -47,13 +51,15 @@ public interface UserBeanLocal { ...@@ -47,13 +51,15 @@ public interface UserBeanLocal {
* ID of the User entity to be searcher * ID of the User entity to be searcher
* @return * @return
*/ */
EventUser findByUserId(Integer userid); EventUser findByUserId(Integer userid, boolean createEventuser);
EventUser findByEventUserId(Integer integer); EventUser findByEventUserId(Integer integer);
GroupMembership findToken(String token); 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); UserImage findUserimageFORCE(Integer id);
...@@ -70,12 +76,13 @@ public interface UserBeanLocal { ...@@ -70,12 +76,13 @@ public interface UserBeanLocal {
List<Role> findUsersRoles(EventUser u); 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 * @param user
* @return * @return
*/ */
EventUser getEventUser(User user); EventUser getEventUser(User user, boolean create);
EventUser validateUser(String username, String password); EventUser validateUser(String username, String password);
...@@ -101,4 +108,23 @@ public interface UserBeanLocal { ...@@ -101,4 +108,23 @@ public interface UserBeanLocal {
boolean isUserInRole(EventUser user, Integer roleId); 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 { ...@@ -15,7 +15,7 @@ public interface VotingBeanLocal {
public void addEntry(CompoEntry compoEntry, CompoEntryFile compoEntryFile); public void addEntry(CompoEntry compoEntry, CompoEntryFile compoEntryFile);
public List<Compo> getCompoList(); public List<Compo> getCompoList(boolean showHidden);
public Compo getCompoById(Integer compoId); public Compo getCompoById(Integer compoId);
...@@ -33,6 +33,10 @@ public interface VotingBeanLocal { ...@@ -33,6 +33,10 @@ public interface VotingBeanLocal {
public Vote saveVote(CompoEntry entry, Integer vote); 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; ...@@ -4,6 +4,7 @@ import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.enums.DatabaseHasCompare; import fi.codecrew.moya.enums.DatabaseHasCompare;
import fi.codecrew.moya.enums.DatabaseValueCompare; import fi.codecrew.moya.enums.DatabaseValueCompare;
import fi.codecrew.moya.model.Role; import fi.codecrew.moya.model.Role;
...@@ -18,10 +19,24 @@ public class UserSearchQuery extends SearchQuery { ...@@ -18,10 +19,24 @@ public class UserSearchQuery extends SearchQuery {
private boolean placeAssoc = false; private boolean placeAssoc = false;
private boolean usersWithUnusedCodes = false; private boolean usersWithUnusedCodes = false;
private DatabaseHasCompare requireImage = DatabaseHasCompare.NONE; private DatabaseHasCompare requireImage = DatabaseHasCompare.NONE;
private List<CardState> hasCardState = new ArrayList<>();
private BigDecimal accountSaldo; private BigDecimal accountSaldo;
private DatabaseValueCompare accountSaldoCompare = DatabaseValueCompare.NONE; 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() public DatabaseValueCompare[] getAccountCompareValues()
{ {
return DatabaseValueCompare.values(); return DatabaseValueCompare.values();
...@@ -38,11 +53,11 @@ public class UserSearchQuery extends SearchQuery { ...@@ -38,11 +53,11 @@ public class UserSearchQuery extends SearchQuery {
public boolean isUsersWithUnusedCodes() { public boolean isUsersWithUnusedCodes() {
return usersWithUnusedCodes; return usersWithUnusedCodes;
} }
public void setUsersWithUnusedCodes(boolean usersWithUnusedCodes) { public void setUsersWithUnusedCodes(boolean usersWithUnusedCodes) {
this.usersWithUnusedCodes = usersWithUnusedCodes; this.usersWithUnusedCodes = usersWithUnusedCodes;
} }
public List<Role> getFilterRoles() { public List<Role> getFilterRoles() {
return filterRoles; return filterRoles;
} }
...@@ -83,4 +98,12 @@ public class UserSearchQuery extends SearchQuery { ...@@ -83,4 +98,12 @@ public class UserSearchQuery extends SearchQuery {
this.requireImage = requireImage; 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= ...@@ -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_annotation=0
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 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_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_arguments_in_qualified_allocation_expression=16
org.eclipse.jdt.core.formatter.alignment_for_assignment=0 org.eclipse.jdt.core.formatter.alignment_for_assignment=0
org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 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 ...@@ -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_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_cases=true
org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false 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_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_local_variable=insert
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=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 ...@@ -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_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.number_of_empty_lines_to_preserve=1
org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true 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.tabulation.size=4
org.eclipse.jdt.core.formatter.use_on_off_tags=false org.eclipse.jdt.core.formatter.use_on_off_tags=false
org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
......
cleanup_settings_version=2 cleanup_settings_version=2
eclipse.preferences.version=1 eclipse.preferences.version=1
formatter_profile=_InsomniaConventions formatter_profile=_Insomnia
formatter_settings_version=12 formatter_settings_version=12
...@@ -30,208 +30,211 @@ import org.eclipse.persistence.annotations.OptimisticLockingType; ...@@ -30,208 +30,211 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS) @OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class AccountEvent extends GenericEntity { public class AccountEvent extends GenericEntity {
private static final long serialVersionUID = 2588419823225148100L; private static final long serialVersionUID = 2588419823225148100L;
@Column(name = "cash", nullable = false) @Column(name = "cash", nullable = false)
private boolean cash = false; private boolean cash = false;
/** /**
* What 1 unit of this product costs. * What 1 unit of this product costs.
*/ */
@Column(name = "unit_price", nullable = false, precision = 24, scale = 4) @Column(name = "unit_price", nullable = false, precision = 24, scale = 4)
private BigDecimal unitPrice; private BigDecimal unitPrice;
/** /**
* The units of the product, eg 1.345 (l), 5 (units) 888.32 (g).. * The units of the product, eg 1.345 (l), 5 (units) 888.32 (g)..
*/ */
@Column(name = "quantity", nullable = false, precision = 24, scale = 4) @Column(name = "quantity", nullable = false, precision = 24, scale = 4)
private BigDecimal quantity; private BigDecimal quantity;
/** /**
* The time this AccountEvent is created. * The time this AccountEvent is created.
*/ */
@Column(name = "event_time", nullable = false) @Column(name = "event_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Calendar eventTime = Calendar.getInstance(); private Calendar eventTime = Calendar.getInstance();
/** /**
* Is the product delivered to the user. * Is the product delivered to the user.
*/ */
@Column(name = "delivered") @Column(name = "delivered")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Calendar delivered; private Calendar delivered;
@Column(name = "delivered_count", nullable = false, precision = 24, scale = 4) @Column(name = "delivered_count", nullable = false, precision = 24, scale = 4)
private BigDecimal deliveredCount = new BigDecimal(0); private BigDecimal deliveredCount = new BigDecimal(0);
/** /**
* If this AccountEvent is a product in foodwace, this field is a reference * If this AccountEvent is a product in foodwace, this field is a reference
* to that foodwave. * to that foodwave.
*/ */
@JoinColumn(name = "food_wave_id", referencedColumnName = FoodWave.ID_COLUMN) @JoinColumn(name = "food_wave_id", referencedColumnName = FoodWave.ID_COLUMN)
@ManyToOne @ManyToOne
private FoodWave foodWave; private FoodWave foodWave;
/** /**
* The product user has acquired and this this AccountEvent is a reference * The product user has acquired and this this AccountEvent is a reference
* to. * to.
*/ */
@JoinColumn(name = "product_id", referencedColumnName = Product.ID_COLUMN, nullable = false) @JoinColumn(name = "product_id", referencedColumnName = Product.ID_COLUMN, nullable = false)
@ManyToOne(optional = false) @ManyToOne(optional = false)
private Product product; private Product product;
/** /**
* The user that bought the products. * The user that bought the products.
*/ */
@JoinColumn(name = "eventuser_id", referencedColumnName = EventUser.ID_COLUMN, nullable = false) @JoinColumn(name = "eventuser_id", referencedColumnName = EventUser.ID_COLUMN, nullable = false)
@ManyToOne(optional = false) @ManyToOne(optional = false)
private EventUser user; private EventUser user;
/** /**
* Who sold the items to the user. * Who sold the items to the user.
*/ */
@JoinColumn(name = "seller_eventuser_id", referencedColumnName = EventUser.ID_COLUMN) @JoinColumn(name = "seller_eventuser_id", referencedColumnName = EventUser.ID_COLUMN)
@ManyToOne(optional = true) @ManyToOne(optional = true)
private EventUser seller; private EventUser seller;
/** /**
* What discounts user has for this account event. Some magic is applied to * What discounts user has for this account event. Some magic is applied to
* calculate these.. :) * calculate these.. :)
*/ */
@OneToMany(mappedBy = "accountEvent", cascade = CascadeType.ALL) @OneToMany(mappedBy = "accountEvent", cascade = CascadeType.ALL)
private List<DiscountInstance> discountInstances = new ArrayList<DiscountInstance>(); private List<DiscountInstance> discountInstances = new ArrayList<DiscountInstance>();
/** /**
* When user has paid a bill a Account event for product "Credit" is created * When user has paid a bill a Account event for product "Credit" is created
* and reference to that bill is here.. * and reference to that bill is here..
*/ */
@OneToOne(mappedBy = "accountEvent") @OneToOne(mappedBy = "accountEvent")
private Bill bill; private Bill bill;
@Lob @Lob
private String description; private String description;
public BigDecimal getTotal() { public BigDecimal getTotal() {
return getQuantity().multiply(getUnitPrice()); return getQuantity().multiply(getUnitPrice());
} }
public AccountEvent() { public AccountEvent() {
} }
public AccountEvent(EventUser u, Product prod, BigDecimal unitPrice, BigDecimal quantity, Calendar eventTime) { public AccountEvent(EventUser u, Product prod, BigDecimal unitPrice, BigDecimal quantity, Calendar eventTime) {
this.setUnitPrice(unitPrice); if (!u.getEvent().equals(prod.getEvent())) {
this.setQuantity(quantity); throw new RuntimeException("User and product are not in the same event!");
this.product = prod; }
this.eventTime = eventTime; this.setUnitPrice(unitPrice);
this.user = u; this.setQuantity(quantity);
} this.product = prod;
this.eventTime = eventTime;
public Calendar getEventTime() { this.user = u;
return eventTime; }
}
public Calendar getEventTime() {
public void setEventTime(Calendar eventTime) { return eventTime;
this.eventTime = eventTime; }
}
public void setEventTime(Calendar eventTime) {
public Calendar getDelivered() { this.eventTime = eventTime;
return delivered; }
}
public Calendar getDelivered() {
public void setDelivered(Calendar delivered) { return delivered;
this.delivered = delivered; }
}
public void setDelivered(Calendar delivered) {
public EventUser getUser() { this.delivered = delivered;
return user; }
}
public EventUser getUser() {
public void setUser(EventUser usersId) { return user;
this.user = usersId; }
}
public void setUser(EventUser usersId) {
public List<DiscountInstance> getDiscountInstances() { this.user = usersId;
return discountInstances; }
}
public List<DiscountInstance> getDiscountInstances() {
public void setDiscountInstances(List<DiscountInstance> discountInstanceList) { return discountInstances;
this.discountInstances = discountInstanceList; }
}
public void setDiscountInstances(List<DiscountInstance> discountInstanceList) {
public void setFoodWave(FoodWave foodWave) { this.discountInstances = discountInstanceList;
this.foodWave = foodWave; }
}
public void setFoodWave(FoodWave foodWave) {
public FoodWave getFoodWave() { this.foodWave = foodWave;
return foodWave; }
}
public FoodWave getFoodWave() {
public void setProduct(Product product) { return foodWave;
this.product = product; }
}
public void setProduct(Product product) {
public Product getProduct() { this.product = product;
return product; }
}
public Product getProduct() {
public void setSeller(EventUser seller) { return product;
this.seller = seller; }
}
public void setSeller(EventUser seller) {
public EventUser getSeller() { this.seller = seller;
return seller; }
}
public EventUser getSeller() {
public void setBill(Bill bill) { return seller;
this.bill = bill; }
}
public void setBill(Bill bill) {
public Bill getBill() { this.bill = bill;
return bill; }
}
public Bill getBill() {
public void setUnitPrice(BigDecimal unitPrice) { return bill;
this.unitPrice = unitPrice; }
}
public void setUnitPrice(BigDecimal unitPrice) {
public BigDecimal getUnitPrice() { this.unitPrice = unitPrice;
return unitPrice; }
}
public BigDecimal getUnitPrice() {
public void setQuantity(BigDecimal quantity) { return unitPrice;
this.quantity = quantity; }
}
public void setQuantity(BigDecimal quantity) {
public BigDecimal getQuantity() { this.quantity = quantity;
return quantity; }
}
public BigDecimal getQuantity() {
public void setCash(boolean cash) { return quantity;
this.cash = cash; }
}
public void setCash(boolean cash) {
public boolean isCash() { this.cash = cash;
return cash; }
}
public boolean isCash() {
public String getDescription() { return cash;
return description; }
}
public String getDescription() {
public void setDescription(String description) { return description;
this.description = description; }
}
public void setDescription(String description) {
public BigDecimal getDeliveredCount() { this.description = description;
return deliveredCount; }
}
public BigDecimal getDeliveredCount() {
return deliveredCount;
}
public void setDeliveredCount(BigDecimal deliveredCount) { public void setDeliveredCount(BigDecimal deliveredCount) {
this.deliveredCount = deliveredCount; this.deliveredCount = deliveredCount;
} }
public boolean isEventDelivered() { public boolean isEventDelivered() {
return (delivered != null); 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; ...@@ -9,14 +9,59 @@ import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType; import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity @Entity
@Table(name = "card_barcode") @Table(name = "card_code")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS) @OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CardBarcode extends GenericEntity { public class CardCode extends GenericEntity {
private static final long serialVersionUID = 4771609802672223277L;
private static final long serialVersionUID = 307145499023412008L;
private ReaderType type;
private String code;
public static final String EVENT_ID_COLUMN = "event_id";
@ManyToOne @ManyToOne
@JoinColumn(name = EVENT_ID_COLUMN, nullable = false)
private LanEvent event;
@ManyToOne()
@JoinColumn(name = "printed_cards_id") @JoinColumn(name = "printed_cards_id")
private PrintedCard printedCard; 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() { public PrintedCard getPrintedCard() {
return printedCard; return printedCard;
...@@ -25,4 +70,7 @@ public class CardBarcode extends GenericEntity { ...@@ -25,4 +70,7 @@ public class CardBarcode extends GenericEntity {
public void setPrintedCard(PrintedCard printedCard) { public void setPrintedCard(PrintedCard printedCard) {
this.printedCard = printedCard; this.printedCard = printedCard;
} }
} }
...@@ -5,7 +5,6 @@ ...@@ -5,7 +5,6 @@
package fi.codecrew.moya.model; package fi.codecrew.moya.model;
import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
...@@ -31,200 +30,212 @@ import org.eclipse.persistence.annotations.OptimisticLockingType; ...@@ -31,200 +30,212 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@Table(name = "compos") @Table(name = "compos")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS) @OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class Compo extends GenericEntity { public class Compo extends GenericEntity {
private static final long serialVersionUID = 2L; private static final long serialVersionUID = 2L;
/** /**
* Name of the competition. * Name of the competition.
*/ */
@Column(name = "compo_name", nullable = false) @Column(name = "compo_name", nullable = false)
private String name; private String name;
public static final String EVENT_ID_COLUMN = "event_id"; public static final String EVENT_ID_COLUMN = "event_id";
@ManyToOne() @ManyToOne()
@JoinColumn(name = EVENT_ID_COLUMN, nullable = false) @JoinColumn(name = EVENT_ID_COLUMN, nullable = false)
private LanEvent event; private LanEvent event;
/** /**
* Start time of the competition Submitting entries should be disabled after * Start time of the competition Submitting entries should be disabled after
* this time. * this time.
*/ */
@Column(name = "compo_start") @Column(name = "compo_start")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date startTime; private Date startTime;
@Column(name = "compo_end") @Column(name = "compo_end")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date endTime; private Date endTime;
/** /**
* When the voting should start * When the voting should start
* *
* @see {@link #holdVoting} * @see {@link #holdVoting}
*/ */
@Column(name = "vote_start") @Column(name = "vote_start")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date voteStart; private Date voteStart;
@Column(name = "vote_end") @Column(name = "vote_end")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date voteEnd; private Date voteEnd;
@Column(name = "submit_start") @Column(name = "submit_start")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date submitStart; private Date submitStart;
@Column(name = "submit_end") @Column(name = "submit_end")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date submitEnd; private Date submitEnd;
@Lob @Lob
@Column(name = "description") @Column(name = "description")
private String description; private String description;
@Column(name = "max_participant_count") @Column(name = "max_participant_count")
private int maxParticipantCount; private int maxParticipantCount;
/** /**
* If ( for some unimaginable reason ) compo is delayed hold voting can be * 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 * used to postpone the start of the voting from the time specified in
* {@link #voteStart} * {@link #voteStart}
*/ */
@Column(name = "hold_voting", nullable = false) @Column(name = "hold_voting", nullable = false)
private boolean holdVoting = true; private boolean holdVoting = false;
/** @Column(name = "hidden", nullable = false)
* Entries submitted to participate this compo. private boolean hidden = false;
*/
@OneToMany(cascade = CascadeType.ALL, mappedBy = "compo") public boolean isHidden() {
@OrderBy("sort") return hidden;
private List<CompoEntry> compoEntries; }
public Compo(String compoName, boolean holdVoting) { public void setHidden(boolean hidden) {
this(); this.hidden = hidden;
}
this.name = compoName;
this.holdVoting = holdVoting; /**
} * Entries submitted to participate this compo.
*/
public boolean isSubmit() @OneToMany(cascade = CascadeType.ALL, mappedBy = "compo")
{ @OrderBy("sort")
Calendar now = Calendar.getInstance(); private List<CompoEntry> compoEntries;
return now.after(getSubmitStart()) && now.before(getSubmitEnd());
} public Compo(String compoName, boolean holdVoting) {
this();
public boolean isVote()
{ this.name = compoName;
Calendar now = Calendar.getInstance(); this.holdVoting = holdVoting;
return !getHoldVoting() && }
now.after(getVoteStart()) &&
now.before(getVoteEnd()); public boolean isSubmit()
} {
Date now = new Date();
public Compo() { return now.after(getSubmitStart()) && now.before(getSubmitEnd());
super(); }
}
public boolean isVote()
public String getName() { {
return name; Date now = new Date();
} return !getHoldVoting() &&
now.after(getVoteStart()) &&
public void setName(String compoName) { now.before(getVoteEnd());
this.name = compoName; }
}
public Compo() {
public Date getStartTime() { super();
return startTime; }
}
public String getName() {
public void setStartTime(Date compoStart) { return name;
this.startTime = compoStart; }
}
public void setName(String compoName) {
public Date getVoteStart() { this.name = compoName;
return voteStart; }
}
public Date getStartTime() {
public void setVoteStart(Date voteStart) { return startTime;
this.voteStart = voteStart; }
}
public void setStartTime(Date compoStart) {
public Date getVoteEnd() { this.startTime = compoStart;
return voteEnd; }
}
public Date getVoteStart() {
public void setVoteEnd(Date voteEnd) { return voteStart;
this.voteEnd = voteEnd; }
}
public void setVoteStart(Date voteStart) {
public Date getSubmitStart() { this.voteStart = voteStart;
return submitStart; }
}
public Date getVoteEnd() {
public void setSubmitStart(Date submitStart) { return voteEnd;
this.submitStart = submitStart; }
}
public void setVoteEnd(Date voteEnd) {
public Date getSubmitEnd() { this.voteEnd = voteEnd;
return submitEnd; }
}
public Date getSubmitStart() {
public void setSubmitEnd(Date submitEnd) { return submitStart;
this.submitEnd = submitEnd; }
}
public void setSubmitStart(Date submitStart) {
public boolean getHoldVoting() { this.submitStart = submitStart;
return holdVoting; }
}
public Date getSubmitEnd() {
public void setHoldVoting(boolean holdVoting) { return submitEnd;
this.holdVoting = holdVoting; }
}
public void setSubmitEnd(Date submitEnd) {
public List<CompoEntry> getCompoEntries() { this.submitEnd = submitEnd;
return compoEntries; }
}
public boolean getHoldVoting() {
public void setCompoEntries(List<CompoEntry> compoEntryList) { return holdVoting;
this.compoEntries = compoEntryList; }
}
public void setHoldVoting(boolean holdVoting) {
public void setDescription(String description) { this.holdVoting = holdVoting;
this.description = description; }
}
public List<CompoEntry> getCompoEntries() {
public String getDescription() { return compoEntries;
return description; }
}
public void setCompoEntries(List<CompoEntry> compoEntryList) {
/** this.compoEntries = compoEntryList;
* @return the maxParticipantCount }
*/
public int getMaxParticipantCount() { public void setDescription(String description) {
return maxParticipantCount; this.description = description;
} }
/** public String getDescription() {
* @param maxParticipantCount return description;
* the maxParticipantCount to set }
*/
public void setMaxParticipantCount(int maxParticipantCount) { /**
this.maxParticipantCount = maxParticipantCount; * @return the maxParticipantCount
} */
public int getMaxParticipantCount() {
public LanEvent getEvent() { return maxParticipantCount;
return event; }
}
/**
public void setEvent(LanEvent event) { * @param maxParticipantCount
this.event = event; * the maxParticipantCount to set
} */
public void setMaxParticipantCount(int maxParticipantCount) {
public Date getEndTime() { this.maxParticipantCount = maxParticipantCount;
return endTime; }
}
public LanEvent getEvent() {
public void setEndTime(Date endTime) { return event;
this.endTime = endTime; }
}
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; ...@@ -11,7 +11,6 @@ import java.util.List;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.Lob; import javax.persistence.Lob;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
...@@ -23,7 +22,6 @@ import javax.persistence.TemporalType; ...@@ -23,7 +22,6 @@ import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking; import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType; import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
/** /**
* *
...@@ -32,170 +30,155 @@ import org.eclipse.persistence.annotations.PrivateOwned; ...@@ -32,170 +30,155 @@ import org.eclipse.persistence.annotations.PrivateOwned;
@Table(name = "compo_entries") @Table(name = "compo_entries")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS) @OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CompoEntry extends GenericEntity { 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) @JoinColumn(name = "compo_id", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false) @ManyToOne(optional = false)
private Compo compo; private Compo compo;
@Column(name = "entry_created", nullable = false) @Column(name = "entry_created", nullable = false)
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Calendar created = Calendar.getInstance(); 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) @Column(name = "final_position")
private String title = ""; private Integer finalPosition;
@Column(name = "author") @JoinColumn(name = "current_file_id", referencedColumnName = CompoEntryFile.ID_COLUMN)
private String author = ""; @OneToOne
private CompoEntryFile currentFile;
@Lob
@Column(name = "notes") @OneToMany(mappedBy = "compoEntry")
private String notes = ""; private List<Vote> votes;
//
@Lob // @PrivateOwned
@Column(name = "screen_message") // @OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", fetch =
private String screenMessage = ""; // FetchType.LAZY)
// private List<CompoEntryFile> files;
@Column(name = "sort")
private Integer sort = 10; @OneToMany(cascade = CascadeType.ALL, mappedBy = "entry")
private List<CompoEntryParticipant> participants;
@Column(name = "final_position")
private Integer finalPosition; @JoinColumn(name = "creator_eventuser_id", referencedColumnName = EventUser.ID_COLUMN, nullable = false)
@ManyToOne
@JoinColumn(name = "current_file_id", referencedColumnName = CompoEntryFile.ID_COLUMN) private EventUser creator;
@OneToOne
private CompoEntryFile currentFile; public Integer getVotetotal()
{
@OneToMany(mappedBy = "compoEntry") int votetotal = 0;
private List<Vote> votes; for (Vote v : getVotes()) {
votetotal += v.getScore();
@PrivateOwned }
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", fetch = FetchType.LAZY) return votetotal;
private List<CompoEntryFile> files; }
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entry") public CompoEntry() {
private List<CompoEntryParticipant> participants; super();
}
@JoinColumn(name = "creator_eventuser_id", referencedColumnName = EventUser.ID_COLUMN, nullable = false)
@ManyToOne public Calendar getCreated() {
private EventUser creator; return created;
}
public Integer getVotetotal()
{ public void setCreated(Calendar entryCreated) {
int votetotal = 0; this.created = entryCreated;
for (Vote v : getVotes()) { }
votetotal += v.getScore();
} public String getNotes() {
return votetotal; return notes;
} }
public CompoEntry() { public void setNotes(String notes) {
super(); this.notes = notes;
} }
public Calendar getCreated() { public String getScreenMessage() {
return created; return screenMessage;
} }
public void setCreated(Calendar entryCreated) { public void setScreenMessage(String screenMessage) {
this.created = entryCreated; this.screenMessage = screenMessage;
} }
public String getNotes() { public Integer getSort() {
return notes; return sort;
} }
public void setNotes(String notes) { public void setSort(Integer sort) {
this.notes = notes; this.sort = sort;
} }
public String getScreenMessage() { public List<Vote> getVotes() {
return screenMessage; return votes;
} }
public void setScreenMessage(String screenMessage) { public void setVotes(List<Vote> voteList) {
this.screenMessage = screenMessage; this.votes = voteList;
} }
public Integer getSort() { public List<CompoEntryParticipant> getParticipants() {
return sort; return participants;
} }
public void setSort(Integer sort) { public void setParticipants(
this.sort = sort; List<CompoEntryParticipant> compoEntryParticipantList) {
} this.participants = compoEntryParticipantList;
}
public List<Vote> getVotes() {
return votes; public Compo getCompo() {
} return compo;
}
public void setVotes(List<Vote> voteList) {
this.votes = voteList; public void setCompo(Compo composId) {
} this.compo = composId;
}
public List<CompoEntryFile> getFiles() {
return files; public EventUser getCreator() {
} return creator;
}
public void setFiles(List<CompoEntryFile> compoEntryFileList) {
this.files = compoEntryFileList; public void setCreator(EventUser creator) {
} this.creator = creator;
}
public List<CompoEntryParticipant> getParticipants() {
return participants; public void setFinalPosition(Integer finalPosition) {
} this.finalPosition = finalPosition;
}
public void setParticipants(
List<CompoEntryParticipant> compoEntryParticipantList) { public Integer getFinalPosition() {
this.participants = compoEntryParticipantList; return finalPosition;
} }
public Compo getCompo() { public String getTitle() {
return compo; return title;
} }
public void setCompo(Compo composId) { public void setTitle(String title) {
this.compo = composId; this.title = title;
} }
public EventUser getCreator() { public String getAuthor() {
return creator; return author;
} }
public void setCreator(EventUser creator) { public void setAuthor(String author) {
this.creator = creator; this.author = author;
} }
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;
}
} }
...@@ -5,10 +5,14 @@ ...@@ -5,10 +5,14 @@
package fi.codecrew.moya.model; package fi.codecrew.moya.model;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar; import java.util.Calendar;
import javax.persistence.Basic;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.Lob; import javax.persistence.Lob;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
...@@ -16,8 +20,11 @@ import javax.persistence.Table; ...@@ -16,8 +20,11 @@ import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import org.apache.commons.codec.binary.Hex;
import org.eclipse.persistence.annotations.OptimisticLocking; import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType; import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* *
...@@ -26,94 +33,110 @@ import org.eclipse.persistence.annotations.OptimisticLockingType; ...@@ -26,94 +33,110 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@Table(name = "compo_entry_files") @Table(name = "compo_entry_files")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS) @OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CompoEntryFile extends GenericEntity { public class CompoEntryFile extends GenericEntity {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@Column(name = "mime_type") @Column(name = "mime_type")
private String mimeType; private String mimeType;
@Column(name = "file_name") @Column(name = "file_name")
private String fileName; private String fileName;
@Lob @Lob
@Column(name = "description") @Column(name = "description")
private String description; private String description;
@Column(name = "hash") @Column(name = "hash", updatable = false)
private String hash; private String hash;
@Lob @Lob
@Column(name = "file_data") @Column(name = "file_data", updatable = false)
private byte[] fileData; @Basic(fetch = FetchType.LAZY)
private byte[] fileData;
@Column(name = "uploaded", nullable = false)
@Temporal(TemporalType.TIMESTAMP) @Column(name = "uploaded", nullable = false)
private Calendar uploaded = Calendar.getInstance(); @Temporal(TemporalType.TIMESTAMP)
private Calendar uploaded = Calendar.getInstance();
@JoinColumn(name = "entry_id", referencedColumnName = "id", nullable = false, updatable = false)
@ManyToOne(optional = false) @JoinColumn(name = "entry_id", referencedColumnName = "id", nullable = false, updatable = false)
private CompoEntry entry; @ManyToOne(optional = false)
private CompoEntry entry;
public CompoEntryFile() { private static final Logger logger = LoggerFactory.getLogger(CompoEntryFile.class);
super();
} public CompoEntryFile() {
super();
public CompoEntryFile(CompoEntry entry) { }
this.entry = entry;
} public CompoEntryFile(CompoEntry entry) {
this.entry = entry;
public String getMimeType() { }
return mimeType;
} public String getMimeType() {
return mimeType;
public void setMimeType(String mimeType) { }
this.mimeType = mimeType;
} public void setMimeType(String mimeType) {
this.mimeType = mimeType;
public String getFileName() { }
return fileName;
} public String getFileName() {
return fileName;
public void setFileName(String fileName) { }
this.fileName = fileName;
} public void setFileName(String fileName) {
this.fileName = fileName;
public String getDescription() { }
return description;
} public String getDescription() {
return description;
public void setDescription(String description) { }
this.description = description;
} public void setDescription(String description) {
this.description = description;
public String getHash() { }
return hash;
} public String getHash() {
return hash;
public void setHash(String hash) { }
this.hash = hash;
} public void setHash(String hash) {
this.hash = hash;
public byte[] getFileData() { }
return fileData;
} public byte[] getFileData() {
return fileData;
public void setFileData(byte[] fileData) { }
this.fileData = fileData;
} public void setFileData(byte[] fileData) {
this.fileData = fileData;
public Calendar getUploaded() { this.hash = getShaChecksum(fileData);
return uploaded; }
}
public Calendar getUploaded() {
public void setUploaded(Calendar uploaded) { return uploaded;
this.uploaded = uploaded; }
}
public void setUploaded(Calendar uploaded) {
public CompoEntry getEntriesId() { this.uploaded = uploaded;
return entry; }
}
public CompoEntry getEntriesId() {
public void setEntriesId(CompoEntry entriesId) { return entry;
this.entry = entriesId; }
}
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 { ...@@ -8,6 +8,11 @@ public enum LanEventPrivatePropertyKey {
CHECKOUT_FI_MERCHANT_PASSWORD(Type.TEXT, null), CHECKOUT_FI_MERCHANT_PASSWORD(Type.TEXT, null),
CHECKOUT_FI_MERCHANT_ID(Type.TEXT, null), CHECKOUT_FI_MERCHANT_ID(Type.TEXT, null),
CHECKOUT_FI_KEY_EXPIRE(Type.DATE, 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 { private enum Type {
......
package fi.codecrew.moya.model; package fi.codecrew.moya.model;
public enum LanEventPropertyKey { public enum LanEventPropertyKey {
EVENT_LOGO(Type.DATA, null), EVENT_LOGO(Type.DATA, null),
INVITEMAIL_SUBJECT(Type.TEXT, "Invitation to Moya Online Youth Accumulator"), 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}."), 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_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!"), 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_ADDRESS(Type.TEXT, "moya@codecrew.fi"),
PORTAL_EMAIL_NAME(Type.TEXT, "Moya Online Youth Accumulator"), PORTAL_EMAIL_NAME(Type.TEXT, "Moya Online Youth Accumulator"),
ADMIN_MAIL(Type.TEXT, "moya@codecrew.fi"), ADMIN_MAIL(Type.TEXT, "moya@codecrew.fi"),
EVENT_LAYOUT(Type.TEXT, "template1"), EVENT_LAYOUT(Type.TEXT, "template1"),
SHOP_DEFAULT_CASH(Type.BOOL, null), SHOP_DEFAULT_CASH(Type.BOOL, null),
PLACECODE_FROM_USER(Type.BOOL, "1"), PLACECODE_FROM_USER(Type.BOOL, "1"),
PLACECODE_PRINT_ONLY_OWN(Type.BOOL, null), PLACECODE_PRINT_ONLY_OWN(Type.BOOL, null),
CHECK_BILL_STATS_PERMISSION(Type.BOOL, null), CHECK_BILL_STATS_PERMISSION(Type.BOOL, null),
GATHER_OTHER_BILL_INFO(Type.BOOL, null), GATHER_OTHER_BILL_INFO(Type.BOOL, null),
ALLOW_BILLING(Type.BOOL, null), ALLOW_BILLING(Type.BOOL, null),
BILL_EXPIRE_HOURS(Type.LONG, "168"), BILL_EXPIRE_HOURS(Type.LONG, "168"),
TEMPLATE_PROPERTY1(Type.TEXT, null), TEMPLATE_PROPERTY1(Type.TEXT, null),
TEMPLATE_PROPERTY2(Type.TEXT, null), TEMPLATE_PROPERTY2(Type.TEXT, null),
TEMPLATE_PROPERTY3(Type.TEXT, null), TEMPLATE_PROPERTY3(Type.TEXT, null),
TEMPLATE_PROPERTY4(Type.TEXT, null), TEMPLATE_PROPERTY4(Type.TEXT, null),
TEMPLATE_PROPERTY5(Type.TEXT, null), TEMPLATE_PROPERTY5(Type.TEXT, null),
INVITE_ONLY_EVENT(Type.BOOL, null),
; ;
private enum Type { private enum Type {
TEXT, DATE, DATA, BOOL, LONG TEXT, DATE, DATA, BOOL, LONG
}; };
private final String defaultvalue; private final String defaultvalue;
private final Type type; private final Type type;
public boolean isText() { public boolean isText() {
return Type.TEXT.equals(type); return Type.TEXT.equals(type);
} }
public boolean isDate() { public boolean isDate() {
return Type.DATE.equals(type); return Type.DATE.equals(type);
} }
public boolean isData() { public boolean isData() {
return Type.DATA.equals(type); return Type.DATA.equals(type);
} }
public boolean isBoolean() { public boolean isBoolean() {
return Type.BOOL.equals(type); return Type.BOOL.equals(type);
} }
public boolean isLong() {
return Type.LONG.equals(type);
}
private LanEventPropertyKey(Type t, String def) public boolean isLong() {
{ return Type.LONG.equals(type);
this.type = t; }
defaultvalue = def;
}
public String getDefaultvalue() { private LanEventPropertyKey(Type t, String def)
return defaultvalue; {
} this.type = t;
defaultvalue = def;
}
public Type getType() { public String getDefaultvalue() {
return type; return defaultvalue;
} }
public Type getType() {
return type;
}
} }
...@@ -57,6 +57,28 @@ public class OrgRole extends GenericEntity { ...@@ -57,6 +57,28 @@ public class OrgRole extends GenericEntity {
@ManyToMany(mappedBy = "orgRoles") @ManyToMany(mappedBy = "orgRoles")
private List<Role> eventRoles; 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() { public OrgRole() {
super(); super();
} }
......
...@@ -51,19 +51,19 @@ public class PrintedCard extends GenericEntity { ...@@ -51,19 +51,19 @@ public class PrintedCard extends GenericEntity {
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Calendar printTime; private Calendar printTime;
@Column(name = "barcode")
private String barcode;
@Column(name = "card_enabled", nullable = false) @Column(name = "card_enabled", nullable = false)
private boolean enabled = true; private boolean enabled = true;
@Column(name = "rfid_uid")
private String rfidUid;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "printedCard") @OneToMany(cascade = CascadeType.ALL, mappedBy = "printedCard")
private List<ReaderEvent> readerEvents = new ArrayList<ReaderEvent>(); 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; private int printCount = 0;
@JoinColumn(name = "current_location_id", referencedColumnName = "id") @JoinColumn(name = "current_location_id", referencedColumnName = "id")
...@@ -112,13 +112,6 @@ public class PrintedCard extends GenericEntity { ...@@ -112,13 +112,6 @@ public class PrintedCard extends GenericEntity {
this.printTime = printTime; this.printTime = printTime;
} }
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public boolean getEnabled() { public boolean getEnabled() {
return enabled; return enabled;
...@@ -128,14 +121,6 @@ public class PrintedCard extends GenericEntity { ...@@ -128,14 +121,6 @@ public class PrintedCard extends GenericEntity {
this.enabled = cardEnabled; this.enabled = cardEnabled;
} }
public String getRfidUid() {
return rfidUid;
}
public void setRfidUid(String rfidUid) {
this.rfidUid = rfidUid;
}
public List<ReaderEvent> getReaderEvents() { public List<ReaderEvent> getReaderEvents() {
return readerEvents; return readerEvents;
} }
...@@ -152,6 +137,17 @@ public class PrintedCard extends GenericEntity { ...@@ -152,6 +137,17 @@ public class PrintedCard extends GenericEntity {
this.currentLocation = currentLocation; this.currentLocation = currentLocation;
} }
public List<CardCode> getCardCodes() {
return cardCodes;
}
public void setCardCodes(List<CardCode> cardCodes) {
this.cardCodes = cardCodes;
}
public EventUser getUser() { public EventUser getUser() {
return user; return user;
} }
...@@ -175,34 +171,7 @@ public class PrintedCard extends GenericEntity { ...@@ -175,34 +171,7 @@ public class PrintedCard extends GenericEntity {
public int getPrintCount() { public int getPrintCount() {
return printCount; 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() { public CardState getCardState() {
return cardState; return cardState;
...@@ -212,21 +181,4 @@ public class PrintedCard extends GenericEntity { ...@@ -212,21 +181,4 @@ public class PrintedCard extends GenericEntity {
this.cardState = cardState; 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; package fi.codecrew.moya.model;
import java.util.Calendar; import java.beans.Transient;
import java.util.Date; import java.util.Date;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.Lob; import javax.persistence.Lob;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
...@@ -23,121 +25,181 @@ import org.eclipse.persistence.annotations.OptimisticLockingType; ...@@ -23,121 +25,181 @@ import org.eclipse.persistence.annotations.OptimisticLockingType;
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS) @OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class ReaderEvent extends GenericEntity { public class ReaderEvent extends GenericEntity {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@Column(name = "event_time", nullable = false) @Column(name = "event_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date time; private Date time;
@Column(name = "event_updated") @Column(name = "event_updated")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date updatetime; private Date updatetime;
@Column(name = "value") @Column(name = "value")
private String value; private String value;
@Lob @Lob
@Column(name = "notes") @Column(name = "notes")
private String notes; private String notes;
@Column(nullable = false) @JoinColumn(name = "printed_cards_id", referencedColumnName = "id", nullable = true, updatable = false)
private Integer gamePoint = 0; @ManyToOne()
private PrintedCard printedCard;
@JoinColumn(name = "printed_cards_id", referencedColumnName = "id", nullable = true, updatable = false)
@ManyToOne(optional = false) @JoinColumn(name = "readers_id", referencedColumnName = "id", nullable = false, updatable = false)
private PrintedCard printedCard; @ManyToOne(optional = false)
private Reader reader;
@JoinColumn(name = "readers_id", referencedColumnName = "id", nullable = false, updatable = false)
@ManyToOne(optional = false) @JoinColumn(name = "event_users_id", referencedColumnName = "id", nullable = true, updatable = false)
private Reader reader; @ManyToOne()
private EventUser user;
public ReaderEvent(Calendar eventTime, PrintedCard card, Reader reader) {
this.time = eventTime.getTime(); @JoinColumn(name = "places_id", referencedColumnName = "id", nullable = true, updatable = false)
this.printedCard = card; @ManyToOne()
this.reader = reader; private Place place;
}
@JoinColumn(name = "products_id", referencedColumnName = "id", nullable = true, updatable = false)
public ReaderEvent() { @ManyToOne()
super(); private Product product;
}
@Enumerated(EnumType.STRING)
public String getNotes() { private ReaderEventType type;
return notes;
} public ReaderEvent(Date eventTime, Reader reader, String value) {
public void setNotes(String notes) { this(eventTime, reader, value, null, null, null, null, ReaderEventType.UNKNOWN);
this.notes = notes;
} }
public Date getTime() { public ReaderEvent(Date eventTime, Reader reader, String value, ReaderEventType type) {
return time;
} this(eventTime, reader, value, null, null, null, null, type);
public void setTime(Date eventTime) { }
this.time = eventTime;
} public ReaderEvent(Date eventTime, Reader reader, String value, PrintedCard card, EventUser user, Place place, Product product, ReaderEventType type) {
public String getValue() { this.time = eventTime;
return value; this.reader = reader;
} this.value = value;
this.user = user;
public void setValue(String value) { this.printedCard = card;
this.value = value; this.user = user;
} this.place = place;
this.product = product;
public PrintedCard getPrintedCard() {
return printedCard; if (type == null)
} type = ReaderEventType.UNKNOWN;
public void setPrintedCard(PrintedCard printedCardsId) { this.type = type;
this.printedCard = printedCardsId;
} }
public Reader getReader() { public ReaderEvent() {
return reader; super();
} }
public void setReader(Reader readersId) { public EventUser getUser() {
this.reader = readersId; return user;
} }
public void setGamePoint(Integer gamePoint) { public void setUser(EventUser user) {
this.gamePoint = gamePoint; this.user = user;
} }
public Integer getGamePoint() { public Place getPlace() {
return gamePoint; return place;
} }
public Date getUpdatetime() { public void setPlace(Place place) {
return updatetime; this.place = place;
} }
public void setUpdatetime(Date updatetime) { public Product getProduct() {
this.updatetime = updatetime; return product;
} }
public String getSeenSince() { public void setProduct(Product product) {
Date comptime = updatetime; this.product = product;
if (comptime == null) }
{
comptime = time; public ReaderEventType getType() {
} return type;
long diffSec = (new Date().getTime() - comptime.getTime()) / 1000; }
long secs = diffSec % 60;
long diffMin = diffSec / 60; public void setType(ReaderEventType type) {
long mins = diffMin % 60; this.type = type;
long hours = diffMin / 60; }
StringBuilder ret = new StringBuilder(); public String getNotes() {
if (hours > 0) { return notes;
ret.append(hours).append(" h "); }
}
if (hours > 0 || mins > 0) { public void setNotes(String notes) {
ret.append(mins).append(" min "); this.notes = notes;
} }
ret.append(secs).append(" sec");
return ret.toString(); 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!