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 2224 additions and 436 deletions
......@@ -7,3 +7,4 @@
*~
.metadata
/code/*/target/
/code/*/test-output/
No preview for this file type
......@@ -86,13 +86,14 @@ public class MoyaLoginModule extends AppservPasswordLoginModule {
// Authenticate User
MoyaRealm samplerealm = (MoyaRealm) _currentRealm;
if (!authbean.authenticate(_username, new String(_passwd))) {
AuthenticationResult authResult = authbean.authUsername(_username, new String(_passwd));
if (authResult == null || authResult.getUsername() == null) {
// Login fails
throw new LoginException((new StringBuilder())
.append("moya realm:Login Failed for user ")
.append(_username).toString());
}
_username = authResult.getUsername();
// Login succeeds
log((new StringBuilder()).append("MoyaRealm:login succeeded for ")
.append(_username).toString());
......@@ -100,7 +101,7 @@ public class MoyaLoginModule extends AppservPasswordLoginModule {
// Get group names for the authenticated user from the Realm class
Enumeration<String> enumeration = null;
try {
enumeration = samplerealm.getGroupNames(_username);
enumeration = samplerealm.getGroupNames(_username, authResult.getUsertype());
} catch (InvalidOperationException invalidoperationexception) {
throw new LoginException(
(new StringBuilder())
......
......@@ -89,7 +89,7 @@ public class MoyaRealm extends AppservRealm {
*/
@Override
public String getAuthType() {
return "Omnia Lan system authentication Realm";
return "Moya authentication Realm";
}
/**
......@@ -127,4 +127,8 @@ public class MoyaRealm extends AppservRealm {
}
public Enumeration<String> getGroupNames(String username, String usertype) throws InvalidOperationException, NoSuchUserException {
return getAuthBean().getGroupNames(username, usertype);
}
}
package fi.codecrew.moya;
public class AuthenticationResult {
private String username = null;
private String usertype = null;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
}
......@@ -13,4 +13,8 @@ public interface MoyaRealmBeanRemote {
boolean authenticate(String _username, String string);
AuthenticationResult authUsername(String _username, String string);
Enumeration<String> getGroupNames(String username, String usertype);
}
......@@ -36,6 +36,31 @@ public class BootstrapBean implements BootstrapBeanLocal {
dbUpdates.add(new String[] { "ALTER TABLE products ALTER COLUMN vat TYPE NUMERIC(4,3)" });
dbUpdates.add(new String[] { "ALTER TABLE actionlog_messages DROP COLUMN crew" });
dbUpdates.add(new String[] { "delete from application_permissions where application ilike '%terminal%'" });
dbUpdates.add(new String[] {
"ALTER TABLE org_roles ADD ldap_role boolean not null default false",
"ALTER TABLE org_roles ADD ldap_weight integer NOT NULL default 100"
});
// barcodefuckup
dbUpdates.add(new String[] {
"DROP TABLE card_barcode",
"ALTER TABLE printed_cards DROP COLUMN barcode;",
"ALTER TABLE printed_cards DROP COLUMN rfid_uid;",
"ALTER TABLE reader_events ADD COLUMN event_users_id integer REFERENCES event_users(id) DEFAULT null;",
"ALTER TABLE reader_events ADD COLUMN places_id integer REFERENCES places(id) DEFAULT null;",
"ALTER TABLE reader_events ADD COLUMN products_id integer REFERENCES products(id) DEFAULT null;",
"ALTER TABLE reader_events ADD COLUMN type text NOT NULL DEFAULT 'UNKNOWN';",
"ALTER TABLE reader_events DROP COLUMN gamepoint;",
"ALTER TABLE reader_events ALTER COLUMN type DROP DEFAULT;",
});
dbUpdates.add(new String[] {
"delete from menu_navigation where item_id in (select id from menuitem where url in ( '/actionlog/messagelist'))",
"delete from menuitem where url in ('/actionlog/messagelist')",
});
dbUpdates.add(new String[] {
"alter table compos add hidden boolean default false not null"
});
}
@EJB
......@@ -61,7 +86,8 @@ public class BootstrapBean implements BootstrapBeanLocal {
throw new RuntimeException("Sanity check failed! DB is newer than the codebase!");
}
} else {
// DB is up to date by default! We need to mark the current version down though.
// DB is up to date by default! We need to mark the current version
// down though.
dBm = new DBModel();
dBm.setRevision(upIdx);
dbModelFacade.create(dBm);
......
......@@ -189,10 +189,10 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
public CardTemplate getUsersCardtype(EventUser user) {
Set<Role> roles = userbean.localFindUsersRoles(user);
logger.info("Checking roles {} against {}", user, roles);
// logger.info("Checking roles {} against {}", user, roles);
CardTemplate greatestTemplate = null;
for (Role listrole : roles) {
logger.info("Checking role {}", listrole);
// logger.info("Checking role {}", listrole);
if (greatestTemplate == null || (listrole.getCardTemplate() != null && greatestTemplate.getPower() < listrole.getCardTemplate().getPower())) {
greatestTemplate = listrole.getCardTemplate();
}
......
......@@ -138,7 +138,7 @@ public class EventBean implements EventBeanLocal {
@Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT })
public LanEvent mergeChanges(LanEvent event) {
if (!permbean.hasPermission(SpecialPermission.SUPERADMIN) && getCurrentEvent().equals(event)) {
if (!permbean.hasPermission(SpecialPermission.SUPERADMIN) && !getCurrentEvent().equals(event)) {
throw new EJBAccessException("Trying to save another event.");
}
return eventFacade.merge(event);
......@@ -188,7 +188,6 @@ public class EventBean implements EventBeanLocal {
return eventPropertyFacade.find(getCurrentEvent(), property);
}
@Override
public long getPropertyLong(LanEventPropertyKey property)
{
......@@ -202,8 +201,6 @@ public class EventBean implements EventBeanLocal {
return ret;
}
@Override
public String getPropertyString(LanEventPropertyKey property)
{
......@@ -266,4 +263,33 @@ public class EventBean implements EventBeanLocal {
return ret;
}
/**
* If you want this event, user getCurrentEvent() This method should be used
* only in special cases...
*/
@Override
@RolesAllowed(EventPermission.S_MANAGE_EVENT)
public LanEvent getEventById(Integer id) {
return eventFacade.find(id);
}
@Override
@RolesAllowed(EventPermission.S_MANAGE_EVENT)
public LanEvent deleteProperty(LanEventProperty property) {
property = eventPropertyFacade.reload(property);
LanEvent event = property.getEvent();
event.getProperties().remove(property);
eventPropertyFacade.refresh(property);
return event;
}
@Override
@RolesAllowed({ EventPermission.S_MANAGE_PRIVATE_PROPERTIES, EventPermission.S_MANAGE_EVENT })
public LanEvent deletePrivateProperty(LanEventPrivateProperty property) {
LanEventPrivateProperty prop = eventPrivatePropertyFacade.reload(property);
LanEvent event = prop.getEvent();
eventPrivatePropertyFacade.remove(property);
return event;
}
}
......@@ -109,4 +109,12 @@ public class EventMapBean implements EventMapBeanLocal {
public Place updatePlace(Place place) {
return placefacade.merge(place);
}
@Override
@RolesAllowed(MapPermission.S_MANAGE_MAPS)
public void createPlace(Place place) {
EventMap map = eventmapfacade.reload(place.getMap());
map.getPlaces().add(place);
place.setMap(map);
}
}
......@@ -11,18 +11,26 @@ import javax.ejb.Stateless;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.AuthenticationResult;
import fi.codecrew.moya.MoyaRealmBeanRemote;
import fi.codecrew.moya.enums.BortalApplication;
import fi.codecrew.moya.enums.apps.IAppPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.facade.ApiApplicationFacade;
import fi.codecrew.moya.facade.ApiApplicationInstanceFacade;
import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.facade.UserFacade;
import fi.codecrew.moya.model.ApiApplication;
import fi.codecrew.moya.model.ApiApplicationInstance;
import fi.codecrew.moya.model.ApplicationPermission;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.LanEventProperty;
import fi.codecrew.moya.model.LanEventPropertyKey;
import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.utilities.PasswordFunctions;
/**
* Session Bean implementation class SessionHandlerBean
......@@ -48,6 +56,15 @@ public class JaasBean implements MoyaRealmBeanRemote {
@EJB
private EventBeanLocal eventbean;
@EJB
private RestBean restbean;
@EJB
private ApiApplicationFacade appfacade;
@EJB
private ApiApplicationInstanceFacade appInstanceFacade;
@EJB
private EventBean eventorgbean;
public EventUser tryLogin(String username, String password) {
EventUser eventUser = eventUserFacade.findByLogin(username.trim().toLowerCase());
......@@ -69,7 +86,13 @@ public class JaasBean implements MoyaRealmBeanRemote {
eventUser = null;
user = null;
}
if (user != null && eventUser == null)
LanEventProperty inviteonly = eventbean.getProperty(LanEventPropertyKey.INVITE_ONLY_EVENT);
boolean createEventuser = true;
if (inviteonly != null && inviteonly.isBooleanValue()) {
createEventuser = false;
}
if (createEventuser && user != null && eventUser == null)
{
LanEvent event = eventbean.getCurrentEvent();
eventUser = new EventUser(user, event, null);
......@@ -97,15 +120,45 @@ public class JaasBean implements MoyaRealmBeanRemote {
// }
// }
public static enum UserType
{
USER, REST
}
@Override
public boolean authenticate(String username, String password) {
boolean ret = (tryLogin(username, password) != null);
public AuthenticationResult authUsername(String username, String password) {
AuthenticationResult ret = new AuthenticationResult();
ret.setUsertype(UserType.USER.name());
if ((username == null || username.isEmpty()) && password.startsWith("rest:")) {
ret.setUsertype(UserType.REST.name());
ret.setUsername(restAuth(password));
} else {
EventUser retUser = tryLogin(username, password);
if (retUser != null) {
ret.setUsername(retUser.getLogin());
}
}
return ret;
}
@Override
public Enumeration<String> getGroupNames(String user) {
logger.info("Fetching groupNames for user {} event {}", user, eventbean.getCurrentEvent().getName());
public boolean authenticate(String username, String password) {
return (tryLogin(username, password) != null);
}
private String restAuth(String restauth) {
String[] authsplit = restauth.split(":");
if (authsplit.length != 6 || !authsplit[0].equals("rest")) {
return null;
}
return authenticateApp(authsplit[1], authsplit[2], authsplit[3], authsplit[4], authsplit[5]);
}
@Override
public Enumeration<String> getGroupNames(String user, String usertype) {
EventUser usr = eventUserFacade.findByLogin(user.toLowerCase().trim());
HashSet<String> roleset = new HashSet<String>();
roleset.add(UserPermission.ANYUSER.getFullName());
......@@ -119,6 +172,23 @@ public class JaasBean implements MoyaRealmBeanRemote {
roleset.add(SpecialPermission.ANONYMOUS.name());
}
if (usertype != null) {
try {
switch (UserType.valueOf(usertype))
{
case REST:
roleset.add(SpecialPermission.REST.name());
break;
case USER:
break;
default:
throw new RuntimeException("Unknown user type: " + usertype);
}
} catch (Throwable t) {
logger.warn("UserType authentication " + usertype);
}
}
if (!usr.getUser().isAnonymous()) {
// all logged in users should be able to logout :)
roleset.add(UserPermission.LOGOUT.name());
......@@ -152,8 +222,46 @@ public class JaasBean implements MoyaRealmBeanRemote {
Vector<String> retvect = new Vector<String>();
retvect.addAll(roleset);
logger.info("group names for user {}: {}", user, retvect);
logger.debug("group names for user {}: {}", user, retvect);
return retvect.elements();
}
@Override
public Enumeration<String> getGroupNames(String username) {
return getGroupNames(username, null);
}
public String authenticateApp(String pathInfo, String appId, String userId, String appStamp, String mac) {
if (mac == null)
return null;
ApiApplication app = appfacade.findByAppid(appId);
if (app == null)
return null;
ApiApplicationInstance apiInstance = appInstanceFacade.findInstance(app, userId);
if (apiInstance == null)
return null;
if (!app.isEnabled() || !apiInstance.isEnabled())
return null;
String ret = null;
String macSource = PasswordFunctions.mkSeparatedString("+", pathInfo, appId, userId, appStamp, apiInstance.getSecretKey());
String macHash = PasswordFunctions.calculateSha1(macSource);
if (mac.equalsIgnoreCase(macHash))
{
switch (app.getAuthtype()) {
case ORGAUTH:
ret = User.ANONYMOUS_LOGINNAME;
break;
case USERKEY:
if (apiInstance.getEventuser() != null) {
ret = apiInstance.getEventuser().getUser().getLogin();
}
break;
default:
throw new RuntimeException("Unknown application authtype!");
}
}
return ret;
}
}
package fi.codecrew.moya.beans;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import fi.codecrew.moya.beanutil.LdapUserHandler;
import fi.codecrew.moya.model.LanEventPrivatePropertyKey;
/**
* Session Bean implementation class LdapBean
*/
@Stateless
@LocalBean
public class LdapBean implements LdapBeanLocal {
@EJB
private EventBean eventbean;
/**
* Default constructor.
*/
public LdapConnection getConnection() {
String ldapurl = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.LDAP_URL);
String userBase = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.LDAP_USER_OU);
String groupBase = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.LDAP_GROUP_OU);
LdapConnection conn = null;
if (ldapurl != null && !ldapurl.isEmpty() && userBase != null && !userBase.isEmpty() && groupBase != null && !groupBase.isEmpty()) {
String bindDn = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.LDAP_BIND_DN);
String bindPw = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.LDAP_BIND_PW);
conn = new LdapConnection(ldapurl, userBase, groupBase, bindDn, bindPw);
}
return conn;
}
private static class LdapConnection extends LdapUserHandler
{
public LdapConnection(String ldapUri, String userBaseDn, String groupBaseDn, String mgmtUser, String mgmtPass) {
super(ldapUri, userBaseDn, groupBaseDn, mgmtUser, mgmtPass);
}
}
}
......@@ -20,6 +20,7 @@ import fi.codecrew.moya.enums.apps.MapPermission;
import fi.codecrew.moya.enums.apps.PollPermission;
import fi.codecrew.moya.enums.apps.ShopPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.enums.apps.TerminalPermission;
import fi.codecrew.moya.enums.apps.TournamentPermission;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.facade.MenuNavigationFacade;
......@@ -27,8 +28,17 @@ import fi.codecrew.moya.facade.MenuitemFacade;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.MenuNavigation;
// *************************************************
// *** LUE TÄMÄ ENNEN KUN TEET MUUTOKSIA MENUUN! **
// *************************************************
/**
* Session Bean implementation class Menubean
*
* Kaikki sivut pitää olla jossain menussa, muuten menu häviää näkyvistä ko.
* sivulla kokonaan. Älä siis poista sivua vaaan aseta sivu näkymättömäksi:
* .setVisible(false).
*
*
*/
@Stateless
@LocalBean
......@@ -70,7 +80,7 @@ public class MenuBean implements MenuBeanLocal {
private synchronized void initializeMenu() {
//int menusort = 100;
// int menusort = 100;
logger.info("Initializing new default menu");
LanEvent ev = eventbean.getCurrentEvent();
......@@ -83,9 +93,9 @@ public class MenuBean implements MenuBeanLocal {
usermenu.addPage(menuitemfacade.findOrCreate("/checkout/cancel"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/permissionDenied"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/utils/flushCache"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/login"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/loginError"), null).setVisible(false);
// usermenu.addPage(menuitemfacade.findOrCreate("/auth/logout"), null).setVisible(false); // disabled
usermenu.addPage(menuitemfacade.findOrCreate("/auth/logoutResponse"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/resetPassword"), null).setVisible(false);
usermenu.addPage(menuitemfacade.findOrCreate("/auth/resetmailSent"), null).setVisible(false);
......@@ -105,12 +115,15 @@ public class MenuBean implements MenuBeanLocal {
userkauppa.addPage(menuitemfacade.findOrCreate("/shop/createBill"), BillPermission.CREATE_BILL);
userkauppa.addPage(menuitemfacade.findOrCreate("/foodwave/list"), ShopPermission.SHOP_FOODWAVE);
userkauppa.addPage(menuitemfacade.findOrCreate("/bill/list"), BillPermission.VIEW_OWN);
userkauppa.addPage(menuitemfacade.findOrCreate("/user/accountEvents"), UserPermission.VIEW_ACCOUNTEVENTS);
userkauppa.addPage(menuitemfacade.findOrCreate("/bill/edit"), BillPermission.VIEW_OWN).setVisible(false);
userkauppa.addPage(menuitemfacade.findOrCreate("/bill/showBill"), BillPermission.VIEW_OWN).setVisible(false);
userkauppa.addPage(menuitemfacade.findOrCreate("/user/accountEvents"), UserPermission.VIEW_OWN_ACCOUNTEVENTS);
MenuNavigation userPlaces = usermenu.addPage(null, null);
userPlaces.setKey("topnavi.userplaces");
userPlaces.addPage(menuitemfacade.findOrCreate("/place/placemap"), MapPermission.VIEW);
userPlaces.addPage(menuitemfacade.findOrCreate("/place/myGroups"), MapPermission.BUY_PLACES);
userPlaces.addPage(menuitemfacade.findOrCreate("/place/edit"), MapPermission.MANAGE_OTHERS).setVisible(false);
MenuNavigation usercompetitions = usermenu.addPage(null, null);
usercompetitions.setKey("topnavi.competitions");
......@@ -137,12 +150,10 @@ public class MenuBean implements MenuBeanLocal {
tournaments.addPage(menuitemfacade.findOrCreate("/tournaments/participate_multi"), TournamentPermission.PARTICIPATE).setVisible(false);
tournaments.addPage(menuitemfacade.findOrCreate("/tournaments/addTeam"), TournamentPermission.PARTICIPATE).setVisible(false);
/*
* MenuNavigation createuser = usermenu.addPage(null, null);
* createuser.setKey("topnavi.createuser");
* createuser.addPage(menuitemfacade.findOrCreate("/user/create"),
* UserPermission.CREATE_NEW);
*/
MenuNavigation createuser = usermenu.addPage(null, null);
createuser.setKey("topnavi.createuser");
createuser.addPage(menuitemfacade.findOrCreate("/user/create"), UserPermission.CREATE_NEW).setVisible(false);
;
navifacade.create(usermenu);
......@@ -152,7 +163,7 @@ public class MenuBean implements MenuBeanLocal {
MenuNavigation adminmenu = new MenuNavigation(ev, "topmenu.admin", 20);
//user management
// user management
MenuNavigation adminuser = adminmenu.addPage(null, null);
adminuser.setKey("topnavi.usermgmt");
adminuser.addPage(menuitemfacade.findOrCreate("/useradmin/list"), UserPermission.VIEW_ALL);
......@@ -193,7 +204,6 @@ public class MenuBean implements MenuBeanLocal {
adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/list"), ShopPermission.LIST_ALL_PRODUCTS);
adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/create"), ShopPermission.MANAGE_PRODUCTS);
adminShopProducts.addPage(menuitemfacade.findOrCreate("/product/edit"), ShopPermission.MANAGE_PRODUCTS).setVisible(false);
;
MenuNavigation foodnavi = adminshop.addPage(null, null);
foodnavi.setKey("topnavi.foodwave");
......@@ -219,7 +229,8 @@ public class MenuBean implements MenuBeanLocal {
MenuNavigation adminPlaces = adminmenu.addPage(null, null);
adminPlaces.setKey("topnavi.userplaces");
adminPlaces.addPage(menuitemfacade.findOrCreate("/place/adminPlacemap"), UserPermission.VIEW_ALL);
// adminPlaces.addPage(menuitemfacade.findOrCreate("/place/adminGroups"), UserPermission.VIEW_ALL); // todo: make new view for managing
// adminPlaces.addPage(menuitemfacade.findOrCreate("/place/adminGroups"),
// UserPermission.VIEW_ALL); // todo: make new view for managing
MenuNavigation mapnavi = adminPlaces.addPage(null, null);
mapnavi.setKey("topnavi.maps");
......@@ -253,13 +264,7 @@ public class MenuBean implements MenuBeanLocal {
gamenavi.addPage(menuitemfacade.findOrCreate("/license/manageCodes"), LicensePermission.MANAGE);
adminevent.addPage(menuitemfacade.findOrCreate("/eventorg/editEvent"), EventPermission.MANAGE_PROPERTIES);
navifacade.create(adminmenu);
//MenuNavigation shopmenu = new MenuNavigation(ev, "topnavi.shopnavi", menusort = +10);
// shopnavi.addPage(menuitemfacade.findOrCreate("/index3"),
// UserPermission.ANYUSER);
// navifacade.create(shopmenu);
adminevent.addPage(menuitemfacade.findOrCreate("/eventorg/edit"), EventPermission.MANAGE_PROPERTIES).setVisible(false);
MenuNavigation tournamentsadm = adminmenu.addPage(null, null);
tournamentsadm.setKey("tournaments.menutitle");
......@@ -270,6 +275,24 @@ public class MenuBean implements MenuBeanLocal {
tournamentsadm.addPage(menuitemfacade.findOrCreate("/tournaments/admin/edit"), TournamentPermission.MANAGE_ALL).setVisible(false);
tournamentsadm.addPage(menuitemfacade.findOrCreate("/tournaments/admin/delete"), TournamentPermission.MANAGE_ALL).setVisible(false);
tournamentsadm.addPage(menuitemfacade.findOrCreate("/tournaments/admin/editrules"), TournamentPermission.MANAGE_ALL).setVisible(false);
MenuNavigation infoviews = adminmenu.addPage(null, null);
infoviews.setKey("topnavi.infoviews");
infoviews.addPage(menuitemfacade.findOrCreate("/admin/adduser/index"), TerminalPermission.INFO);
MenuNavigation infonavi = infoviews.addPage(null, null);
infonavi.setKey("subnavi.info");
infonavi.addPage(menuitemfacade.findOrCreate("/info/index"), TerminalPermission.INFO);
infonavi.addPage(menuitemfacade.findOrCreate("/info/incoming"), TerminalPermission.INFO);
navifacade.create(adminmenu);
// MenuNavigation shopmenu = new MenuNavigation(ev, "topnavi.shopnavi",
// menusort = +10);
// shopnavi.addPage(menuitemfacade.findOrCreate("/index3"),
// UserPermission.ANYUSER);
// navifacade.create(shopmenu);
/*
* MenuNavigation profileTopmenu = new MenuNavigation(ev,
* "topnavi.profile", menusort = +10);
......@@ -330,6 +353,36 @@ public class MenuBean implements MenuBeanLocal {
}
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// OLD MENU STARTS HERE!!!
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
// ////////////////////////////////////////////////////
private synchronized void initializeOldMenu() {
LanEvent ev = eventbean.getCurrentEvent();
......@@ -346,6 +399,7 @@ public class MenuBean implements MenuBeanLocal {
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/sendResetMail"), UserPermission.LOGIN);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/user/invite"), UserPermission.INVITE_USERS);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/permissionDenied"), null).setVisible(false);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/utils/flushCache"), null).setVisible(false);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/login"), null).setVisible(false);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/loginError"), null).setVisible(false);
frontTopnavi.addPage(menuitemfacade.findOrCreate("/auth/logout"), null).setVisible(false);
......
......@@ -38,6 +38,7 @@ import fi.codecrew.moya.model.User;
UserPermission.S_MODIFY,
UserPermission.S_MODIFY_ACCOUNTEVENTS,
UserPermission.S_VIEW_ACCOUNTEVENTS,
UserPermission.S_VIEW_OWN_ACCOUNTEVENTS,
UserPermission.S_VIEW_ALL,
UserPermission.S_VIEW_SELF,
UserPermission.S_WRITE_ROLES,
......@@ -165,7 +166,8 @@ public class PermissionBean implements PermissionBeanLocal {
}
/**
* Makes sure default user and public role exist and the user is member of the role.
* Makes sure default user and public role exist and the user is member of
* the role.
*/
@Override
public EventUser getAnonEventUser() {
......
......@@ -113,9 +113,12 @@ public class PlaceBean implements PlaceBeanLocal {
}
/**
* Calculate the price of reserved places for the user Optional parameter newPlace can be given when the place is added to the price calculations;
* Calculate the price of reserved places for the user Optional parameter
* newPlace can be given when the place is added to the price calculations;
*
* User parameter can be used to select another user than the currently logged in user, but if user does not have enough rights an exception will be thrown
* User parameter can be used to select another user than the currently
* logged in user, but if user does not have enough rights an exception will
* be thrown
*
*/
......@@ -182,7 +185,8 @@ public class PlaceBean implements PlaceBeanLocal {
}
/**
* Reserve the place for user. This reservation will timeout after a while buy() method should be called after this when buying place;
* Reserve the place for user. This reservation will timeout after a while
* buy() method should be called after this when buying place;
*
* @param place
* place to be reserved
......@@ -196,7 +200,15 @@ public class PlaceBean implements PlaceBeanLocal {
place = placeFacade.find(place.getId());
user = eventUserFacade.find(user.getId());
boolean ret = false;
if (place.isBuyable() && !place.isTaken()) {
// when admin click's place, he reserves it -> just ignore it
if (!place.isTaken() || (permbean.hasPermission(MapPermission.MANAGE_OTHERS) && permbean.getCurrentUser().equals(place.getCurrentUser()))) {
if (place.isBuyable() || permbean.hasPermission(MapPermission.MANAGE_OTHERS)) {
if (!place.isBuyable()) {
place.setBuyable(true);
}
place.setCurrentUser(user);
place.setReleaseTime(Calendar.getInstance());
place.getReleaseTime().add(Calendar.MINUTE, RESERVE_MINUTES);
......@@ -215,6 +227,7 @@ public class PlaceBean implements PlaceBeanLocal {
}
ret = true;
}
}
return ret;
}
......@@ -237,10 +250,22 @@ public class PlaceBean implements PlaceBeanLocal {
// logger.debug("timeouting places");
// placeFacade.releasePlaces(permbean.getCurrentUser());
// }
@Override
@RolesAllowed({ MapPermission.S_BUY_PLACES, MapPermission.S_MANAGE_OTHERS })
public PlaceGroup buySelectedPlaces(EventUser user) throws BortalCatchableException {
return buyOrReserveSelectedPlaces(user, true);
}
@Override
@RolesAllowed({ MapPermission.S_MANAGE_OTHERS })
public PlaceGroup reserveSelectedPlaces(EventUser eventuser) throws BortalCatchableException {
return buyOrReserveSelectedPlaces(eventuser, false);
}
/**
* Reserves places and creates accountevents for the places.
*/
public PlaceGroup buyOrReserveSelectedPlaces(EventUser user, boolean createAccountevents) throws BortalCatchableException {
if (user == null) {
user = permbean.getCurrentUser();
} else {
......@@ -258,7 +283,8 @@ public class PlaceBean implements PlaceBeanLocal {
}
// PlaceGroup pg = pgbean.createPlaceGroup(user);
if (createAccountevents)
{
BigDecimal totalprice = addAndCalcPrice(user, null);
BigDecimal balance = user.getAccountBalance();
if (balance.compareTo(totalprice) < 0 && !permbean.hasPermission(MapPermission.MANAGE_OTHERS)) {
......@@ -269,7 +295,7 @@ public class PlaceBean implements PlaceBeanLocal {
for (Entry<Product, Integer> line : getPlaceProductcount(places).entrySet()) {
productPBean.createAccountEvent(line.getKey(), new BigDecimal(line.getValue()), user, Calendar.getInstance());
}
}
PlaceGroup pg = new PlaceGroup(event, Calendar.getInstance(), Calendar.getInstance(), true);
pg.setCreator(user);
pgfacade.create(pg);
......@@ -346,12 +372,17 @@ public class PlaceBean implements PlaceBeanLocal {
private static boolean isUserMember(EventUser user, Product prod) {
boolean ret = false;
if (user.getGroupMemberships() != null)
{
for (GroupMembership gm : user.getGroupMemberships()) {
if (prod.equals(gm.getPlaceReservation().getProduct())) {
if (gm.getPlaceReservation() != null && prod.equals(gm.getPlaceReservation().getProduct())) {
ret = true;
break;
}
}
}
return ret;
}
......@@ -527,7 +558,8 @@ public class PlaceBean implements PlaceBeanLocal {
PDF pdf = new PDF(outputStream);
pdf.setTitle("Place");
float pointInMillim = (25.4f / 72.0f); // 1 point is 1/72 inches. 1 inch = 25.4mm
float pointInMillim = (25.4f / 72.0f); // 1 point is 1/72 inches. 1 inch
// = 25.4mm
float pagex = width / pointInMillim;
float pagey = height / pointInMillim;
......@@ -563,7 +595,7 @@ public class PlaceBean implements PlaceBeanLocal {
font.setSize(font2);
textLine = new TextLine(font);
textLine.setText(barcodeBean.getPlaceHexcode(place));
textLine.setText(barcodeBean.getPlaceTextCode(place));
textLine.setPosition(currentX, (pagey / 2) + font1);
textLine.setColor(new int[] { 0, 0, 0 });
textLine.drawOn(page);
......@@ -586,4 +618,5 @@ public class PlaceBean implements PlaceBeanLocal {
throw new RuntimeException(e);
}
}
}
......@@ -34,13 +34,12 @@ import fi.codecrew.moya.model.LanEventPropertyKey;
import fi.codecrew.moya.model.PlaceGroup;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.utilities.BarcodeUtils;
import fi.codecrew.moya.utilities.I18n;
/**
* Session Bean implementation class PlaceGroupBean
*/
@Stateless
@DeclareRoles({ SpecialPermission.S_USER, MapPermission.S_BUY_PLACES })
@DeclareRoles({ SpecialPermission.S_USER, MapPermission.S_BUY_PLACES, MapPermission.S_MANAGE_MAPS })
public class PlaceGroupBean implements PlaceGroupBeanLocal {
private static final Logger logger = LoggerFactory.getLogger(PlaceGroupBean.class);
......@@ -87,7 +86,7 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
// }
@Override
@RolesAllowed(SpecialPermission.S_USER)
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public List<GroupMembership> getMembershipsAndCreations(EventUser user) {
if (user == null) {
user = permbean.getCurrentUser();
......@@ -99,7 +98,7 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public List<GroupMembership> getMemberships(EventUser user) {
if (user == null) {
user = permbean.getCurrentUser();
......@@ -133,7 +132,7 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public void getGroupMembershipPdf(EventUser usr, OutputStream ostream) {
List<GroupMembership> memberships = getMembershipsAndCreations(usr);
......@@ -161,13 +160,12 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
Font titlefont = new Font(pdf, CoreFont.TIMES_ROMAN);
titlefont.setSize(20);
Page page = new Page(pdf, A4.PORTRAIT);
int y = YSTART;
String titletext = "Lipputositteet";
if(printOnlyOwn || memberships.size() <= 1) {
if (printOnlyOwn || memberships.size() <= 1) {
titletext = "Lipputosite";
}
......@@ -177,7 +175,6 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
y += 30;
for (GroupMembership membership : memberships) {
if (y > 750) {
......@@ -185,7 +182,7 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
y = YSTART;
}
if(printOnlyOwn && (membership.getUser() == null || !membership.getUser().equals(usr))) {
if (printOnlyOwn && (membership.getUser() == null || !membership.getUser().equals(usr))) {
continue;
}
......@@ -195,15 +192,15 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
// logger.debug("Jpeg: " + jpeg.getWidth() + " h. " +
// jpeg.getHeight());
if(placecodeFromUser) {
if(membership.getUser() != null) {
if (placecodeFromUser) {
if (membership.getUser() != null) {
Image image = new Image(pdf, barcodeBean.getUserBarcode(membership.getUser()), ImageType.PNG);
image.scaleBy(0.8);
image.setPosition(50, y);
image.drawOn(page);
} else {
TextLine nouser = new TextLine(bigfont, "EMPTY PLACE" );
nouser.setPosition(85, y+10);
TextLine nouser = new TextLine(bigfont, "EMPTY PLACE");
nouser.setPosition(85, y + 10);
nouser.drawOn(page);
}
} else {
......@@ -213,8 +210,6 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
image.drawOn(page);
}
StringBuilder sb = new StringBuilder();
if (membership.getPlaceReservation().getName() != null)
{
......@@ -252,11 +247,9 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
y = YSTART;
}
String footertext = "Nämä lipputositteenne tulee olla tulostettuna paperille kun saavutte tapahtumaan.";
if(printOnlyOwn || memberships.size() <= 1) {
if (printOnlyOwn || memberships.size() <= 1) {
footertext = "Tämä henkilökohtainen lipputositteesi tulee olla mukana tulostettuna paperille kun saavut tapahtumaan.";
}
......@@ -272,19 +265,20 @@ public class PlaceGroupBean implements PlaceGroupBeanLocal {
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public void releaseAndGenerateToken(GroupMembership gmem) {
gmem = gmemfacade.find(gmem.getId());
gmem = gmemfacade.reload(gmem);
if (!(permbean.getCurrentUser().getId().equals(gmem.getPlaceGroup().getCreator().getId()) || permbean.hasPermission(MapPermission.MANAGE_OTHERS))) {
loggerbean.logMessage(SecurityLogType.permissionDenied, permbean.getCurrentUser(), "User tried to release and generate group membership: " + gmem);
throw new EJBAccessException("Not enough rights to release token");
}
gmem.setUser(null);
gmem.setInviteToken(gmemfacade.createInviteToken());
logger.info("Place released. {} new token {}", gmem.getInviteToken());
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
@RolesAllowed({ SpecialPermission.S_USER, MapPermission.S_MANAGE_MAPS })
public List<PlaceGroup> getPlacegroups(EventUser user) {
return pgfacade.find(user);
}
......
......@@ -104,6 +104,9 @@ public class ProductBean implements ProductBeanLocal {
@EJB
private DiscountBean discountBean;
@EJB
private CardTemplateBean cardTemplateBean;
private static final Logger logger = LoggerFactory.getLogger(ProductBean.class);
/**
......@@ -350,6 +353,7 @@ public class ProductBean implements ProductBeanLocal {
public AccountEvent createAccountEvent(Product product, BigDecimal quantity, EventUser user) {
user = eventUserFacade.reload(user);
AccountEvent ret = productPBean.createAccountEvent(product, quantity, user, Calendar.getInstance());
cardTemplateBean.checkPrintedCard(user);
return ret;
}
......
......@@ -100,10 +100,8 @@ public class ProductPBean {
// discountinstancefacade.create(discInst);
accEventdiscounts.add(new DiscountInstance(ret, d));
}
if (user.getAccountEvents() == null) {
user.setAccountEvents(new ArrayList<AccountEvent>());
}
user.getAccountEvents().add(ret);
user.addAccountevent(ret);
accounteventfacade.create(ret);
logger.debug("create ac {} for user {}", ret, user.getUser());
// flush changes to db.
......
package fi.codecrew.moya.beans;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.ejb.Singleton;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.facade.ApiApplicationFacade;
import fi.codecrew.moya.facade.ApiApplicationInstanceFacade;
import fi.codecrew.moya.utilities.PasswordFunctions;
/**
* Session Bean implementation class RestAuthBean
*/
@Singleton
@LocalBean
public class RestBean implements RestBeanLocal {
/**
* Default constructor.
*/
public RestBean() {
// TODO Auto-generated constructor stub
}
@Resource
private TimerService ts;
@Resource
private SessionContext context;
private static final Logger logger = LoggerFactory.getLogger(RestBean.class);
@PostConstruct
public void initialize() {
ts.createTimer(60 * 1000, 60 * 1000, null);
}
@EJB
private ApiApplicationFacade appfacade;
@EJB
private ApiApplicationInstanceFacade apiInstanceFacade;
@Timeout
public void timeoutNonces(Timer timer) {
int count = 0;
long now = System.currentTimeMillis();
synchronized (userRestAuths) {
for (Map<String, Long> ua : userRestAuths.values()) {
for (Entry<String, Long> no : ua.entrySet()) {
if (no != null && now > no.getValue()) {
ua.remove(no.getKey());
++count;
}
}
}
}
logger.info("Timeouted {} nonces", count);
}
// Username -> Nonce -> expiration
private Map<String, Map<String, Long>> userRestAuths = Collections.synchronizedMap(new HashMap<String, Map<String, Long>>());
@Override
public String getLoggedinUserRestNonce()
{
String username = context.getCallerPrincipal().getName();
if (username == null) {
return null;
}
Map<String, Long> userAuthMap = userRestAuths.get(username);
if (userAuthMap == null) {
synchronized (userRestAuths) {
if (!userRestAuths.containsKey(username)) {
userAuthMap = Collections.synchronizedMap(new HashMap<String, Long>());
userRestAuths.put(username, userAuthMap);
}
}
}
Random random = new Random();
int charcount = 20 + random.nextInt(10);
String nonce = null;
do {
nonce = PasswordFunctions.generateRandomString(charcount, PasswordFunctions.ALL_CHARS);
} while (userAuthMap.containsKey(nonce));
userAuthMap.put(nonce, System.currentTimeMillis() + 120 * 1000); // Timeout in 60 seconds.
return nonce;
}
@Override
public boolean validateUserNonce(String nonce) {
String username = context.getCallerPrincipal().getName();
boolean ret = false;
// Validation is successfull if user exists, nonce exists and timeout has not passed.
if (username != null && userRestAuths.containsKey(username)) {
Long time = userRestAuths.get(username).remove(nonce);
ret = time != null && time > System.currentTimeMillis();
}
return ret;
}
}
......@@ -21,6 +21,7 @@ import org.slf4j.LoggerFactory;
import fi.codecrew.moya.enums.apps.IAppPermission;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.facade.RoleFacade;
import fi.codecrew.moya.facade.UserFacade;
import fi.codecrew.moya.model.ApplicationPermission;
......@@ -51,6 +52,15 @@ public class RoleBean implements RoleBeanLocal {
@EJB
private UserFacade userFacade;
@EJB
private EventUserFacade eventuserfacade;
@EJB
private EventBeanLocal permbean;
@EJB
private CardTemplateBean cardTemplateBean;
// VIEW_ALL pitää olla että voidaan hakea roolien perusteella.
@Override
@RolesAllowed({ UserPermission.S_READ_ROLES, UserPermission.S_VIEW_ALL })
......@@ -161,6 +171,28 @@ public class RoleBean implements RoleBeanLocal {
return role;
}
private void checkRoleLdap()
{
}
@Override
@RolesAllowed(UserPermission.S_WRITE_ROLES)
public Role addRole(EventUser eventuser, Role role)
{
eventuser = eventuserfacade.reload(eventuser);
role = roleFacade.reload(role);
if (!eventuser.getRoles().contains(role)) {
eventuser.getRoles().add(role);
}
if (!role.getUsers().contains(eventuser)) {
role.getUsers().add(eventuser);
}
cardTemplateBean.checkPrintedCard(eventuser);
return role;
}
@Override
@RolesAllowed(UserPermission.S_WRITE_ROLES)
public void saveRoles(EventUser usr, List<Role> usersRoles) {
......@@ -176,6 +208,8 @@ public class RoleBean implements RoleBeanLocal {
ur.getUsers().remove(usr);
}
}
cardTemplateBean.checkPrintedCard(usr);
}
@Override
......
......@@ -59,6 +59,7 @@ public class VotingBean implements VotingBeanLocal {
voteFacade.create(v);
}
@RolesAllowed(CompoPermission.S_MANAGE)
public void createCompo(Compo c) {
c.setEvent(eventBean.getCurrentEvent());
compoFacade.create(c);
......@@ -73,15 +74,15 @@ public class VotingBean implements VotingBeanLocal {
c.getCompoEntries().add(compoEntry);
compoFacade.flush();
compoEntryFile.setEntriesId(compoEntry);
compoEntry.getFiles().add(compoEntryFile);
// compoEntry.getFiles().add(compoEntryFile);
}
public Compo getCompoById(Integer compoId) {
return compoFacade.find(compoId);
}
public List<Compo> getCompoList() {
return compoFacade.getList();
public List<Compo> getCompoList(boolean showHidden) {
return compoFacade.getList(showHidden);
}
@Override
......@@ -129,16 +130,17 @@ public class VotingBean implements VotingBeanLocal {
return compoEntryFacade.find(entryId);
}
@Override
public CompoEntry findEntryWithFiles(Integer entryId) {
CompoEntry ret = compoEntryFacade.find(entryId);
logger.debug("Found files {}", ret.getFiles().size());
return ret;
}
// @Override
// public CompoEntry findEntryWithFiles(Integer entryId) {
// CompoEntry ret = compoEntryFacade.find(entryId);
// // logger.debug("Found files {}", ret.getFiles().size());
//
// return ret;
//
// }
@Override
@RolesAllowed(CompoPermission.S_MANAGE)
public CompoEntry saveSort(CompoEntry e) {
CompoEntry entry = compoEntryFacade.find(e.getId());
entry.setSort(e.getSort());
......@@ -177,4 +179,15 @@ public class VotingBean implements VotingBeanLocal {
return voteEntity;
}
@Override
@RolesAllowed(CompoPermission.S_MANAGE)
public Compo saveCompo(Compo compo) {
return compoFacade.merge(compo);
}
@Override
public void create(CompoEntryFile cef) {
compoEntryFileFacade.create(cef);
}
}
package fi.codecrew.moya.facade;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.ApiApplication;
import fi.codecrew.moya.model.ApiApplication_;
@Stateless
@LocalBean
public class ApiApplicationFacade extends IntegerPkGenericFacade<ApiApplication> {
public ApiApplicationFacade() {
super(ApiApplication.class);
}
public ApiApplication findByAppid(String appId) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<ApiApplication> q = cb.createQuery(ApiApplication.class);
Root<ApiApplication> root = q.from(ApiApplication.class);
q.where(cb.equal(root.get(ApiApplication_.applicationKey), appId));
return super.getSingleNullableResult(getEm().createQuery(q));
}
}
package fi.codecrew.moya.facade;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.ApiApplication;
import fi.codecrew.moya.model.ApiApplicationInstance;
import fi.codecrew.moya.model.ApiApplicationInstance_;
@Stateless
@LocalBean
public class ApiApplicationInstanceFacade extends IntegerPkGenericFacade<ApiApplicationInstance> {
public ApiApplicationInstanceFacade() {
super(ApiApplicationInstance.class);
}
public ApiApplicationInstance findInstance(ApiApplication app, String userId) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<ApiApplicationInstance> q = cb.createQuery(ApiApplicationInstance.class);
Root<ApiApplicationInstance> root = q.from(ApiApplicationInstance.class);
q.where(cb.equal(root.get(ApiApplicationInstance_.application), app),
cb.equal(root.get(ApiApplicationInstance_.authname), userId));
return super.getSingleNullableResult(getEm().createQuery(q));
}
}
......@@ -3,14 +3,14 @@ package fi.codecrew.moya.facade;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import fi.codecrew.moya.model.CardBarcode;
import fi.codecrew.moya.model.CardCode;
@Stateless
@LocalBean
public class CardBarcodeFacade extends IntegerPkGenericFacade<CardBarcode> {
public class CardCodeFacade extends IntegerPkGenericFacade<CardCode> {
public CardBarcodeFacade() {
super(CardBarcode.class);
public CardCodeFacade() {
super(CardCode.class);
}
}
package fi.codecrew.moya.facade;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
......@@ -7,11 +8,12 @@ import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.Compo_;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.Compo;
import fi.codecrew.moya.model.Compo_;
@Stateless
@LocalBean
......@@ -23,11 +25,17 @@ public class CompoFacade extends IntegerPkGenericFacade<Compo> {
super(Compo.class);
}
public List<Compo> getList() {
public List<Compo> getList(boolean showHidden) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<Compo> cq = cb.createQuery(Compo.class);
Root<Compo> root = cq.from(Compo.class);
cq.where(cb.equal(root.get(Compo_.event), eventbean.getCurrentEvent()));
ArrayList<Predicate> preds = new ArrayList<>();
preds.add(cb.equal(root.get(Compo_.event), eventbean.getCurrentEvent()));
if (!showHidden) {
preds.add(cb.isFalse(root.get(Compo_.hidden)));
}
cq.where(preds.toArray(new Predicate[preds.size()]));
cq.orderBy(cb.desc(root.get(Compo_.startTime)));
List<Compo> ret = getEm().createQuery(cq).getResultList();
return ret;
......
......@@ -13,15 +13,21 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.enums.DatabaseHasCompare;
import fi.codecrew.moya.enums.DatabaseValueCompare;
import fi.codecrew.moya.facade.callbacks.EventLimiter;
import fi.codecrew.moya.facade.callbacks.EventUserAccountSaldoPredicate;
import fi.codecrew.moya.facade.callbacks.EventUserCardStateFilter;
import fi.codecrew.moya.facade.callbacks.EventUserPlacegroupPredicate;
import fi.codecrew.moya.facade.callbacks.EventUserRolefilter;
import fi.codecrew.moya.facade.callbacks.EventUserSearchPredicate;
import fi.codecrew.moya.facade.callbacks.EventuserToUserWrapper;
import fi.codecrew.moya.facade.callbacks.OrderCallback;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
......@@ -29,6 +35,7 @@ import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.User_;
import fi.codecrew.moya.util.UserSearchQuery;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
......@@ -47,6 +54,7 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
}
private final Map<Integer, Map<String, Integer>> logincache = new HashMap<Integer, Map<String, Integer>>();
private static final Logger logger = LoggerFactory.getLogger(EventUserFacade.class);
public EventUser findByLogin(final String login) {
LanEvent event = eventBean.getCurrentEvent();
......@@ -82,10 +90,13 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
}
public EventUser find(User user) {
LanEvent event = eventBean.getCurrentEvent();
EventUser ret;
if ((ret = checkCache(user.getLogin(), event)) == null)
return getOtherOrganisationsEventuser(user, eventBean.getCurrentEvent());
}
public EventUser getOtherOrganisationsEventuser(User user, LanEvent event)
{
EventUser ret = null;
if ((ret = checkCache(user.getLogin(), event)) == null) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<EventUser> cq = cb.createQuery(EventUser.class);
Root<EventUser> root = cq.from(EventUser.class);
......@@ -108,19 +119,40 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
public SearchResult<EventUser> searchEventUsers(UserSearchQuery query) {
ArrayList<FacadeCallback<EventUser>> callbacks = new ArrayList<FacadeCallback<EventUser>>();
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<EventUser> listCQuery = cb.createQuery(EventUser.class);
CriteriaQuery<Long> countCQuery = cb.createQuery(Long.class);
if (query.getSort() != null)
{
boolean asc = false;
if (query.getSortDirection() != null) {
asc = QuerySortOrder.ASCENDING.equals(query.getSortDirection());
}
SingularAttribute<? super User, ?> sortfield = UserFacade.getUserField(query.getSort());
logger.info("Sortig with {}, asc {} ", sortfield, asc);
callbacks.add(new EventuserToUserWrapper(new OrderCallback<User>(asc, sortfield)));
} else {
callbacks.add(new OrderCallback<EventUser>(false, EventUser_.id));
}
callbacks.add(new EventLimiter(eventBean.getCurrentEvent()));
if (query.getSearch() != null && !query.getSearch().isEmpty())
{
if (query.getSearch() != null && !query.getSearch().isEmpty()) {
callbacks.add(new EventUserSearchPredicate(query.getSearch(), UserFacade.getAttrlist()));
}
if (query.isPlaceAssoc())
{
if (query.isPlaceAssoc()) {
callbacks.add(new EventUserPlacegroupPredicate());
}
if (query.getFilterRoles() != null && !query.getFilterRoles().isEmpty()) {
callbacks.add(new EventUserRolefilter(query.getFilterRoles()));
}
if (query.getHasCardState() != null && !query.getHasCardState().isEmpty()) {
callbacks.add(new EventUserCardStateFilter(query.getHasCardState()));
}
if (query.getAccountSaldo() != null &&
query.getAccountSaldoCompare() != null &&
!DatabaseValueCompare.NONE.equals(query.getAccountSaldoCompare()))
......@@ -132,11 +164,6 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
}
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<EventUser> listCQuery = cb.createQuery(EventUser.class);
CriteriaQuery<Long> countCQuery = cb.createQuery(Long.class);
From<?, EventUser> listRoot = searchCallbacks(listCQuery, callbacks, EventUser.class);
From<?, EventUser> countRoot = searchCallbacks(countCQuery, callbacks, EventUser.class);
......
......@@ -9,10 +9,10 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.OrgRole_;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.EventOrganiser;
import fi.codecrew.moya.model.OrgRole;
import fi.codecrew.moya.model.OrgRole_;
import fi.codecrew.moya.model.User;
/**
......@@ -29,17 +29,19 @@ public class OrgRoleFacade extends IntegerPkGenericFacade<OrgRole> {
super(OrgRole.class);
}
public List<OrgRole> findForUser(User user) {
public List<OrgRole> findForUser(User user, EventOrganiser organisation) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<OrgRole> cq = cb.createQuery(OrgRole.class);
Root<OrgRole> root = cq.from(OrgRole.class);
cq.where(cb.equal(root.get(OrgRole_.eventOrganisation), eventBean
.getCurrentEvent().getOrganiser()), cb.isMember(user,
root.get(OrgRole_.users)));
cq.where(cb.equal(root.get(OrgRole_.eventOrganisation), organisation), cb.isMember(user, root.get(OrgRole_.users)));
return getEm().createQuery(cq).getResultList();
}
public List<OrgRole> findForUser(User user) {
return findForUser(user, eventBean.getCurrentEvent().getOrganiser());
}
public OrgRole createRole(EventOrganiser org, String roleName) {
OrgRole ret = new OrgRole();
ret.setEventOrganisation(org);
......
......@@ -3,7 +3,6 @@ package fi.codecrew.moya.facade;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import javax.ejb.EJB;
......@@ -14,9 +13,12 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.model.CardCode;
import fi.codecrew.moya.model.CardCode_;
import fi.codecrew.moya.model.CardTemplate_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEvent;
......@@ -35,31 +37,19 @@ public class PrintedCardFacade extends IntegerPkGenericFacade<PrintedCard> {
@EJB
private EventBeanLocal eventbean;
public PrintedCard findByRfid(String uid) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<PrintedCard> cq = cb.createQuery(PrintedCard.class);
Root<PrintedCard> root = cq.from(PrintedCard.class);
cq.where(
cb.or(
cb.equal(root.get(PrintedCard_.barcode), uid),
cb.equal(root.get(PrintedCard_.rfidUid), uid)),
cb.equal(root.get(PrintedCard_.event), eventbean.getCurrentEvent()));
return getSingleNullableResult(getEm().createQuery(cq));
}
public PrintedCard findByBarcode(String barcode) {
public PrintedCard findByCode(String code) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<PrintedCard> cq = cb.createQuery(PrintedCard.class);
Root<PrintedCard> root = cq.from(PrintedCard.class);
CriteriaQuery<CardCode> cq = cb.createQuery(CardCode.class);
Root<CardCode> root = cq.from(CardCode.class);
cq.where(cb.equal(root.get(PrintedCard_.barcode), barcode),
cb.equal(root.get(PrintedCard_.event), eventbean.getCurrentEvent()));
cq.where(cb.equal(root.get(CardCode_.code), code),
cb.equal(root.get(CardCode_.event), eventbean.getCurrentEvent()));
return getSingleNullableResult(getEm().createQuery(cq));
CardCode cardcode = getSingleNullableResult(getEm().createQuery(cq));
return (cardcode == null)?null : cardcode.getPrintedCard();
}
public List<PrintedCard> findAllEnabled(LanEvent currentEvent) {
......@@ -85,14 +75,16 @@ public class PrintedCardFacade extends IntegerPkGenericFacade<PrintedCard> {
}
public PrintedCard findLatestByRfidFromAny(String uid) {
public PrintedCard findLatestByCodeFromAny(String code) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<PrintedCard> cq = cb.createQuery(PrintedCard.class);
Root<PrintedCard> root = cq.from(PrintedCard.class);
Root<CardCode> root = cq.from(CardCode.class);
cq.select(root.get(CardCode_.printedCard));
cq.where(cb.equal(root.get(CardCode_.code), code));
cq.where(cb.equal(root.get(PrintedCard_.rfidUid), uid));
cq.orderBy(cb.desc(root.get(PrintedCard_.printTime)));
cq.orderBy(cb.desc(root.get(CardCode_.printedCard).get(PrintedCard_.printTime)));
TypedQuery<PrintedCard> q = getEm().createQuery(cq);
q.setMaxResults(1);
......
......@@ -11,10 +11,11 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.Product_;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.Product;
import fi.codecrew.moya.model.ProductFlag;
import fi.codecrew.moya.model.Product_;
@Stateless
@LocalBean
......@@ -44,11 +45,15 @@ public class ProductFacade extends IntegerPkGenericFacade<Product> {
}
public List<Product> findProductsByPrice(BigDecimal price) {
return findProductsByPrice(price, eventbean.getCurrentEvent());
}
public List<Product> findProductsByPrice(BigDecimal price, LanEvent event) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> root = cq.from(Product.class);
cq.where(cb.equal(root.get(Product_.event), eventbean.getCurrentEvent()),
cq.where(cb.equal(root.get(Product_.event), event),
cb.equal(root.get(Product_.price), price));
return getEm().createQuery(cq).getResultList();
......@@ -72,6 +77,7 @@ public class ProductFacade extends IntegerPkGenericFacade<Product> {
Root<Product> root = cq.from(Product.class);
cq.where(
cb.equal(root.get(Product_.event), eventbean.getCurrentEvent()),
cb.equal(root.get(Product_.barcode), barcode)
);
......
......@@ -31,8 +31,26 @@ public class ReaderEventFacade extends IntegerPkGenericFacade<ReaderEvent> {
cq.orderBy(cb.desc(root.get(ReaderEvent_.time)));
TypedQuery<ReaderEvent> q = getEm().createQuery(cq);
if (count > 0) {
q.setMaxResults(count);
}
return q.getResultList();
}
public List<ReaderEvent> findEventsAfterEvent(Reader reader, Integer eventId) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<ReaderEvent> cq = cb.createQuery(ReaderEvent.class);
Root<ReaderEvent> root = cq.from(ReaderEvent.class);
cq.where(cb.equal(root.get(ReaderEvent_.reader), reader),
cb.gt(root.get(ReaderEvent_.id), eventId));
cq.orderBy(cb.desc(root.get(ReaderEvent_.time)));
TypedQuery<ReaderEvent> q = getEm().createQuery(cq);
return q.getResultList();
}
}
......@@ -15,12 +15,13 @@ import javax.persistence.metamodel.SingularAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.facade.callbacks.OrderCallback;
import fi.codecrew.moya.facade.callbacks.StringSearchPredicateCreator;
import fi.codecrew.moya.model.User_;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.User_;
import fi.codecrew.moya.utilities.SearchQuery;
import fi.codecrew.moya.utilities.SearchQuery.QuerySortOrder;
import fi.codecrew.moya.utilities.SearchResult;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
......@@ -102,11 +103,11 @@ public class UserFacade extends IntegerPkGenericFacade<User> {
public SearchResult<User> searchAllUsers(SearchQuery search) {
List<FacadeCallback<User>> callbacks = new ArrayList<FacadeCallback<User>>();
if (search.getSort() == null || search.getSort().isEmpty()) {
callbacks.add(new OrderCallback<User>(false, User_.id));
} else {
callbacks.add(new OrderCallback<User>(false, search.getSort()));
}
// Ascending if null or not descending..
boolean asc = search.getSortDirection() == null || !QuerySortOrder.DESCENDING.equals(search.getSortDirection());
SingularAttribute<? super User, ?> sortfield = getUserField(search.getSort());
callbacks.add(new OrderCallback<User>(asc, sortfield));
callbacks.add(new StringSearchPredicateCreator<User>(search.getSearch(), getAttrlist()));
return super.searcher(search, callbacks);
......@@ -142,6 +143,68 @@ public class UserFacade extends IntegerPkGenericFacade<User> {
return getEm().createQuery(cq).getResultList();
}
/**
* For example in sorting.
*
* @param fieldname
* @return By default return "id"
*/
public static SingularAttribute<? super User, ?> getUserField(String fieldname) {
SingularAttribute<? super User, ?> sort = User_.id;
if (fieldname != null)
{
switch (fieldname) {
case "created":
sort = User_.created;
break;
case "login":
sort = User_.login;
break;
case "lastname":
sort = User_.lastname;
break;
case "firstnames":
sort = User_.firstnames;
break;
case "birthday":
sort = User_.birthday;
break;
case "nick":
sort = User_.nick;
break;
case "email":
sort = User_.email;
break;
case "address":
sort = User_.address;
break;
case "zip":
sort = User_.zip;
break;
case "postalTown":
sort = User_.postalTown;
break;
case "town":
sort = User_.town;
break;
case "phone":
sort = User_.phone;
break;
case "gender":
sort = User_.gender;
break;
case "confirmTime":
sort = User_.confirmTime;
break;
case "id":
default:
sort = User_.id;
}
}
return sort;
}
// public SearchResult<User> searchEventUsers(SearchQuery query)
// {
// ArrayList<FacadeCallback<EventUser>> callbacks = new
......
......@@ -5,7 +5,7 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
......@@ -27,7 +27,7 @@ public class AndPredicateCreator<A, T extends ModelInterface> implements FacadeC
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, T> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates) {
if (searchval == null || attributes == null || attributes.isEmpty()) {
return;
}
......
......@@ -4,11 +4,11 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
......@@ -21,7 +21,7 @@ public class EventLimiter implements FacadeCallback<EventUser> {
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, EventUser> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
predicates.add(cb.equal(root.get(EventUser_.event), ev));
}
......
......@@ -5,14 +5,14 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import fi.codecrew.moya.model.AccountEvent_;
import fi.codecrew.moya.enums.DatabaseValueCompare;
import fi.codecrew.moya.model.AccountEvent;
import fi.codecrew.moya.model.AccountEvent_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
......@@ -27,7 +27,7 @@ public class EventUserAccountSaldoPredicate implements FacadeCallback<EventUser>
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, EventUser> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
Subquery<BigDecimal> subq = cq.subquery(BigDecimal.class);
Root<AccountEvent> acRoot = subq.from(AccountEvent.class);
subq.where(cb.equal(acRoot.get(AccountEvent_.user), root));
......
package fi.codecrew.moya.facade.callbacks;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.PrintedCard;
import fi.codecrew.moya.model.PrintedCard_;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventUserCardStateFilter implements FacadeCallback<EventUser> {
private final List<CardState> states;
private static final Logger logger = LoggerFactory.getLogger(EventUserCardStateFilter.class);
public EventUserCardStateFilter(List<CardState> statelist) {
this.states = statelist;
}
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
if (states != null && !states.isEmpty())
{
for (CardState s : states)
{
logger.info("Statte {}, type {}", s, s.getClass());
}
logger.debug("Requiring states {}", states);
Path<Integer> rootId = root.get(EventUser_.id);
Subquery<Integer> subq = cq.subquery(Integer.class);
Root<PrintedCard> subroot = subq.from(PrintedCard.class);
subq.select(subroot.join(PrintedCard_.user).get(EventUser_.id));
subq.where(subroot.get(PrintedCard_.cardState).in(states));
predicates.add(rootId.in(subq));
}
}
}
......@@ -4,17 +4,17 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventUserPlacegroupPredicate implements FacadeCallback<EventUser> {
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, EventUser> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
predicates.add(cb.isNotEmpty(root.get(EventUser_.groupMemberships)));
}
......
......@@ -8,7 +8,6 @@ import java.util.Set;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
......@@ -18,13 +17,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.model.AccountEvent_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.GroupMembership_;
import fi.codecrew.moya.model.Place_;
import fi.codecrew.moya.model.Product_;
import fi.codecrew.moya.model.Role_;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.model.Role_;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventUserRolefilter implements FacadeCallback<EventUser> {
......@@ -49,7 +48,7 @@ public class EventUserRolefilter implements FacadeCallback<EventUser> {
return checkedRoles;
}
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, EventUser> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
if (roles != null && !roles.isEmpty())
{
HashSet<Integer> roleids = new HashSet<Integer>();
......
package fi.codecrew.moya.facade.callbacks;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUser_;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventuserToUserWrapper implements FacadeCallback<EventUser> {
private final FacadeCallback<User>[] callbacks;
@SafeVarargs
public EventuserToUserWrapper(FacadeCallback<User>... wrapped)
{
this.callbacks = wrapped;
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates) {
for (FacadeCallback<User> subcallback : callbacks) {
subcallback.exec(cb, cq, root.get(EventUser_.user), predicates);
}
}
}
......@@ -4,7 +4,7 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
......@@ -25,7 +25,7 @@ public class OrPredicateCreator<A, T extends ModelInterface> implements FacadeCa
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, T> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates) {
if (searchstr == null || attributes == null || attributes.isEmpty()) {
return;
}
......
......@@ -4,11 +4,14 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.utilities.jpa.FacadeCallback;
import fi.codecrew.moya.utilities.jpa.ModelInterface;
......@@ -17,6 +20,7 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T
private final SingularAttribute<? super T, ?> sort;
private final boolean asc;
private String sortstr;
private static final Logger logger = LoggerFactory.getLogger(OrderCallback.class);
public OrderCallback(boolean asc, SingularAttribute<? super T, ?> sortAttr) {
sort = sortAttr;
......@@ -31,16 +35,15 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, T> root, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> root, List<Predicate> predicates) {
Class<?> rettype = cq.getResultType();
// Check if returntype is entity or are we for example counting results
if (!ModelInterface.class.isAssignableFrom(rettype))
{
if (!ModelInterface.class.isAssignableFrom(rettype)) {
return;
}
Path<?> path = null;
Expression<?> path = null;
if (sort == null) {
if (sortstr == null) {
return;
......@@ -56,6 +59,9 @@ public class OrderCallback<T extends ModelInterface> implements FacadeCallback<T
if (path == null) {
return;
}
if (path.getJavaType().equals(String.class)) {
path = cb.lower((Expression<String>) path);
}
if (asc) {
cq.orderBy(cb.asc(path));
......
......@@ -5,7 +5,6 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
......@@ -44,7 +43,7 @@ public abstract class PathStringSearchPredicateCreator<T extends ModelInterface,
}
@Override
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, T> path, List<Predicate> predicates) {
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<T> path, List<Predicate> predicates) {
if (searchstr == null || attributes == null || attributes.isEmpty()) {
return;
}
......
......@@ -62,5 +62,11 @@
<artifactId>httpclient</artifactId>
<version>4.3-beta2</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.5</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package fi.codecrew.moya.beans;
import org.testng.annotations.Test;
public class BarcodeTests {
@Test
public void tbd() {
}
}
......@@ -8,6 +8,7 @@ import javax.ejb.Local;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Place;
import fi.codecrew.moya.model.PrintedCard;
import fi.codecrew.moya.model.Product;
@Local
public interface BarcodeBeanLocal {
......@@ -17,8 +18,11 @@ public interface BarcodeBeanLocal {
public InputStream getUserBarcode(EventUser user) throws IOException;
public InputStream getCardBarcode(PrintedCard printedCard) throws IOException;
public String getPlaceHexcode(Place place);
public Place getPlaceFromHexcode(String hexcode);
public String getPlaceTextCode(Place place);
public Place getPlaceFromTextCode(String hexcode);
public String checkVrAuthCode(String code);
public Product getProduct(String barcode);
public Place getPlaceFromBarcode(String barcode);
}
......@@ -9,6 +9,7 @@ import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.model.CardTemplate;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.PrintedCard;
import fi.codecrew.moya.model.ReaderEvent;
import fi.codecrew.moya.utilities.jsf.EntityFinderBean;
@Local
......
......@@ -38,4 +38,10 @@ public interface EventBeanLocal {
long getPropertyLong(LanEventPropertyKey property);
LanEvent getEventById(Integer id);
LanEvent deleteProperty(LanEventProperty property);
LanEvent deletePrivateProperty(LanEventPrivateProperty property);
}
......@@ -24,4 +24,6 @@ public interface EventMapBeanLocal {
Place updatePlace(Place place);
void createPlace(Place create);
}
package fi.codecrew.moya.beans;
import javax.ejb.Local;
@Local
public interface LdapBeanLocal {
}
......@@ -63,10 +63,13 @@ public interface PlaceBeanLocal {
*/
byte[] generatePlacesPdf(float width, float height, double font1, double font2);
// public byte[] generatePlacesPdf(double width, double height, double font1, double font2);
List<GroupMembership> matchGroupMembershipsByInviteToken(String token);
GroupMembership findGroupMembershipsByToken(String token);
PlaceGroup reserveSelectedPlaces(EventUser eventuser) throws BortalCatchableException;
}
......@@ -17,7 +17,7 @@ public interface ReaderBeanLocal {
// ReaderEvent assocTagToPlacecode(String tag, String readerIdent, String
// placecode) throws BortalCatchableException, PermissionDeniedException;
ReaderEvent assocTagToCard(String tag, String readerIdent, PrintedCard card);
ReaderEvent assocCodeToCard(ReaderEvent readerEvent, PrintedCard card);
List<Reader> getReaders();
......@@ -27,7 +27,8 @@ public interface ReaderBeanLocal {
User findTagFromAnyEvent(String value);
ReaderEvent createCard(ReaderEvent event, EventUser user);
// lets comment this out, so I can see where this is going
// ReaderEvent createCard(ReaderEvent event, EventUser user);
Reader getReader(Integer readerid);
......@@ -39,6 +40,12 @@ public interface ReaderBeanLocal {
List<ReaderEvent> getLastReaderEvents();
ReaderEvent checkTag(String readerIdent, String tag);
ReaderEvent checkCode(String readerIdent, String code);
ReaderEvent checkCode(Reader reader, String code);
List<ReaderEvent> getReaderEvents(Integer readerId, Integer count);
List<ReaderEvent> getReaderEventsAfterEvent(Integer readerId, Integer eventId);
}
package fi.codecrew.moya.beans;
import javax.ejb.Local;
@Local
public interface RestBeanLocal {
boolean validateUserNonce(String nonce);
String getLoggedinUserRestNonce();
// String authenticateApp(String pathInfo, String appId, String userid, String applicationStamp, String mac);
}
......@@ -36,4 +36,6 @@ public interface RoleBeanLocal {
public List<Role> getRoles(EventUser selectedUser);
Role addRole(EventUser eventuser, Role role);
}
......@@ -2,6 +2,7 @@ package fi.codecrew.moya.beans;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import javax.ejb.Local;
......@@ -10,6 +11,7 @@ import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Feedback;
import fi.codecrew.moya.model.GameID;
import fi.codecrew.moya.model.GroupMembership;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.model.TournamentGame;
import fi.codecrew.moya.model.User;
......@@ -26,7 +28,7 @@ public interface UserBeanLocal {
SearchResult<User> getUsers(SearchQuery search);
SearchResult<User> getEventUsers(SearchQuery search);
//SearchResult<User> getEventUsers(SearchQuery search);
EventUser mergeChanges(EventUser user);
......@@ -40,6 +42,8 @@ public interface UserBeanLocal {
boolean resetPassword(User user, String password, String hash);
public User getUser(Integer id);
/**
* Search EventUser entity by User entity ID
*
......@@ -47,13 +51,15 @@ public interface UserBeanLocal {
* ID of the User entity to be searcher
* @return
*/
EventUser findByUserId(Integer userid);
EventUser findByUserId(Integer userid, boolean createEventuser);
EventUser findByEventUserId(Integer integer);
GroupMembership findToken(String token);
void createFromToken(EventUser user, String token);
boolean createFromInviteToken(EventUser user, String token);
EventUser acceptInviteForExistingUser(String username, String password, String token);
UserImage findUserimageFORCE(Integer id);
......@@ -70,12 +76,13 @@ public interface UserBeanLocal {
List<Role> findUsersRoles(EventUser u);
/**
* NOTICE! If the user parameter is a persisted object the returned EventUser has a reloaded user, eg changes to the User object are lost!
* NOTICE! If the user parameter is a persisted object the returned
* EventUser has a reloaded user, eg changes to the User object are lost!
*
* @param user
* @return
*/
EventUser getEventUser(User user);
EventUser getEventUser(User user, boolean create);
EventUser validateUser(String username, String password);
......@@ -101,4 +108,23 @@ public interface UserBeanLocal {
boolean isUserInRole(EventUser user, Integer roleId);
EventUser getOtherEventsEventuser(User user, LanEvent event);
/**
* Transfers account saldo from previous event. Creates negative
* accountevent for source user and positive for dst user. There are few
* requirements.
* <ul>
* <li>User must be the same.
* <li>Organisation must be the same.
* <li>All users should have positive or zero balance on source event.
* </ul>
*
* @param source
* @param dst
* @return Saldo transferred. Zero if no transfer was made, Null if there
* was error..
*/
BigDecimal transferAccountSaldoFromPreviousEvent(List<User> dstEventuser, LanEvent source);
}
......@@ -15,7 +15,7 @@ public interface VotingBeanLocal {
public void addEntry(CompoEntry compoEntry, CompoEntryFile compoEntryFile);
public List<Compo> getCompoList();
public List<Compo> getCompoList(boolean showHidden);
public Compo getCompoById(Integer compoId);
......@@ -33,6 +33,10 @@ public interface VotingBeanLocal {
public Vote saveVote(CompoEntry entry, Integer vote);
public CompoEntry findEntryWithFiles(Integer entryId);
//public CompoEntry findEntryWithFiles(Integer entryId);
public Compo saveCompo(Compo compo);
public void create(CompoEntryFile cef);
}
......@@ -4,6 +4,7 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import fi.codecrew.moya.enums.CardState;
import fi.codecrew.moya.enums.DatabaseHasCompare;
import fi.codecrew.moya.enums.DatabaseValueCompare;
import fi.codecrew.moya.model.Role;
......@@ -18,10 +19,24 @@ public class UserSearchQuery extends SearchQuery {
private boolean placeAssoc = false;
private boolean usersWithUnusedCodes = false;
private DatabaseHasCompare requireImage = DatabaseHasCompare.NONE;
private List<CardState> hasCardState = new ArrayList<>();
private BigDecimal accountSaldo;
private DatabaseValueCompare accountSaldoCompare = DatabaseValueCompare.NONE;
public UserSearchQuery() {
super();
}
public CardState[] getCardStates()
{
return CardState.values();
}
public UserSearchQuery(int page, int pagesize, String sort, String search, QuerySortOrder direction) {
super(page, pagesize, sort, search, direction);
}
public DatabaseValueCompare[] getAccountCompareValues()
{
return DatabaseValueCompare.values();
......@@ -83,4 +98,12 @@ public class UserSearchQuery extends SearchQuery {
this.requireImage = requireImage;
}
public List<CardState> getHasCardState() {
return hasCardState;
}
public void setHasCardState(List<CardState> hasCardState) {
this.hasCardState = hasCardState;
}
}
......@@ -15,7 +15,7 @@ org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=1
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
org.eclipse.jdt.core.formatter.alignment_for_assignment=0
org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
......@@ -90,7 +90,7 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false
org.eclipse.jdt.core.formatter.indentation.size=8
org.eclipse.jdt.core.formatter.indentation.size=4
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert
......@@ -283,7 +283,7 @@ org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
org.eclipse.jdt.core.formatter.tabulation.char=space
org.eclipse.jdt.core.formatter.tabulation.char=tab
org.eclipse.jdt.core.formatter.tabulation.size=4
org.eclipse.jdt.core.formatter.use_on_off_tags=false
org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
......
cleanup_settings_version=2
eclipse.preferences.version=1
formatter_profile=_InsomniaConventions
formatter_profile=_Insomnia
formatter_settings_version=12
......@@ -119,6 +119,9 @@ public class AccountEvent extends GenericEntity {
}
public AccountEvent(EventUser u, Product prod, BigDecimal unitPrice, BigDecimal quantity, Calendar eventTime) {
if (!u.getEvent().equals(prod.getEvent())) {
throw new RuntimeException("User and product are not in the same event!");
}
this.setUnitPrice(unitPrice);
this.setQuantity(quantity);
this.product = prod;
......
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,15 +9,60 @@ import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
@Entity
@Table(name = "card_barcode")
@Table(name = "card_code")
@OptimisticLocking(type = OptimisticLockingType.CHANGED_COLUMNS)
public class CardBarcode extends GenericEntity {
private static final long serialVersionUID = 4771609802672223277L;
public class CardCode extends GenericEntity {
private static final long serialVersionUID = 307145499023412008L;
private ReaderType type;
private String code;
public static final String EVENT_ID_COLUMN = "event_id";
@ManyToOne
@JoinColumn(name = EVENT_ID_COLUMN, nullable = false)
private LanEvent event;
@ManyToOne()
@JoinColumn(name = "printed_cards_id")
private PrintedCard printedCard;
public CardCode(PrintedCard card, ReaderType type, String code) {
this.printedCard = card;
this.type = type;
this.code = code;
}
public CardCode() {
}
public ReaderType getType() {
return type;
}
public void setType(ReaderType type) {
this.type = type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public LanEvent getEvent() {
return event;
}
public void setEvent(LanEvent event) {
this.event = event;
}
public PrintedCard getPrintedCard() {
return printedCard;
}
......@@ -25,4 +70,7 @@ public class CardBarcode extends GenericEntity {
public void setPrintedCard(PrintedCard printedCard) {
this.printedCard = printedCard;
}
}
......@@ -5,7 +5,6 @@
package fi.codecrew.moya.model;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
......@@ -91,7 +90,18 @@ public class Compo extends GenericEntity {
* {@link #voteStart}
*/
@Column(name = "hold_voting", nullable = false)
private boolean holdVoting = true;
private boolean holdVoting = false;
@Column(name = "hidden", nullable = false)
private boolean hidden = false;
public boolean isHidden() {
return hidden;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
/**
* Entries submitted to participate this compo.
......@@ -109,13 +119,13 @@ public class Compo extends GenericEntity {
public boolean isSubmit()
{
Calendar now = Calendar.getInstance();
Date now = new Date();
return now.after(getSubmitStart()) && now.before(getSubmitEnd());
}
public boolean isVote()
{
Calendar now = Calendar.getInstance();
Date now = new Date();
return !getHoldVoting() &&
now.after(getVoteStart()) &&
now.before(getVoteEnd());
......@@ -227,4 +237,5 @@ public class Compo extends GenericEntity {
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
}
......@@ -11,7 +11,6 @@ import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
......@@ -23,7 +22,6 @@ import javax.persistence.TemporalType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.eclipse.persistence.annotations.PrivateOwned;
/**
*
......@@ -68,10 +66,11 @@ public class CompoEntry extends GenericEntity {
@OneToMany(mappedBy = "compoEntry")
private List<Vote> votes;
@PrivateOwned
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", fetch = FetchType.LAZY)
private List<CompoEntryFile> files;
//
// @PrivateOwned
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "entry", fetch =
// FetchType.LAZY)
// private List<CompoEntryFile> files;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entry")
private List<CompoEntryParticipant> participants;
......@@ -133,14 +132,6 @@ public class CompoEntry extends GenericEntity {
this.votes = voteList;
}
public List<CompoEntryFile> getFiles() {
return files;
}
public void setFiles(List<CompoEntryFile> compoEntryFileList) {
this.files = compoEntryFileList;
}
public List<CompoEntryParticipant> getParticipants() {
return participants;
}
......@@ -174,14 +165,6 @@ public class CompoEntry extends GenericEntity {
return finalPosition;
}
public void setCurrentFile(CompoEntryFile currentFile) {
this.currentFile = currentFile;
}
public CompoEntryFile getCurrentFile() {
return currentFile;
}
public String getTitle() {
return title;
}
......
......@@ -5,10 +5,14 @@
package fi.codecrew.moya.model;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
......@@ -16,8 +20,11 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.apache.commons.codec.binary.Hex;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
......@@ -37,11 +44,12 @@ public class CompoEntryFile extends GenericEntity {
@Column(name = "description")
private String description;
@Column(name = "hash")
@Column(name = "hash", updatable = false)
private String hash;
@Lob
@Column(name = "file_data")
@Column(name = "file_data", updatable = false)
@Basic(fetch = FetchType.LAZY)
private byte[] fileData;
@Column(name = "uploaded", nullable = false)
......@@ -51,6 +59,7 @@ public class CompoEntryFile extends GenericEntity {
@JoinColumn(name = "entry_id", referencedColumnName = "id", nullable = false, updatable = false)
@ManyToOne(optional = false)
private CompoEntry entry;
private static final Logger logger = LoggerFactory.getLogger(CompoEntryFile.class);
public CompoEntryFile() {
super();
......@@ -98,6 +107,7 @@ public class CompoEntryFile extends GenericEntity {
public void setFileData(byte[] fileData) {
this.fileData = fileData;
this.hash = getShaChecksum(fileData);
}
public Calendar getUploaded() {
......@@ -116,4 +126,17 @@ public class CompoEntryFile extends GenericEntity {
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;
}
}
......@@ -177,6 +177,14 @@ public class EventUser extends GenericEntity {
this.notes = notes;
}
/**
* NOTICE: This returns only manually added roles. If you want to get all
* roles from products, places, etc, use
* {@link fi.codecrew.moya.beans.UserBeanLocal#findUsersRoles(EventUser)
* UserBeanLocal#findUsersRoles(EventUser) }
*
* @return
*/
public List<Role> getRoles() {
return roles;
}
......@@ -451,9 +459,16 @@ public class EventUser extends GenericEntity {
}
public String getShortUserDescriptor() {
StringBuilder sb = new StringBuilder();
sb.append(getNick()).append(" // ").append(getWholeName()).append(" // ").append(getEmail());
return sb.toString();
return user.getShortUserDescriptor();
}
public void addAccountevent(AccountEvent accountevent) {
if (accountEvents == null) {
accountEvents = new ArrayList<AccountEvent>();
}
if (!this.equals(accountevent.getUser())) {
throw new RuntimeException("Trying to add accountevent for eventuser with different eventuser");
}
accountEvents.add(accountevent);
}
}
......@@ -8,6 +8,11 @@ public enum LanEventPrivatePropertyKey {
CHECKOUT_FI_MERCHANT_PASSWORD(Type.TEXT, null),
CHECKOUT_FI_MERCHANT_ID(Type.TEXT, null),
CHECKOUT_FI_KEY_EXPIRE(Type.DATE, null),
LDAP_URL(Type.TEXT, null),
LDAP_BIND_DN(Type.TEXT, null),
LDAP_BIND_PW(Type.TEXT, null),
LDAP_USER_OU(Type.TEXT, null),
LDAP_GROUP_OU(Type.TEXT, null),
;
private enum Type {
......
......@@ -23,6 +23,7 @@ public enum LanEventPropertyKey {
TEMPLATE_PROPERTY3(Type.TEXT, null),
TEMPLATE_PROPERTY4(Type.TEXT, null),
TEMPLATE_PROPERTY5(Type.TEXT, null),
INVITE_ONLY_EVENT(Type.BOOL, null),
;
......
......@@ -57,6 +57,28 @@ public class OrgRole extends GenericEntity {
@ManyToMany(mappedBy = "orgRoles")
private List<Role> eventRoles;
@Column(name = "ldap_role", nullable = false)
private boolean ldapRole = false;
@Column(name = "ldap_weight", nullable = false)
private int ldapWeight = 100;
public boolean isLdapRole() {
return ldapRole;
}
public void setLdapRole(boolean ldapRole) {
this.ldapRole = ldapRole;
}
public int getLdapWeight() {
return ldapWeight;
}
public void setLdapWeight(int ldapWeight) {
this.ldapWeight = ldapWeight;
}
public OrgRole() {
super();
}
......
......@@ -51,18 +51,18 @@ public class PrintedCard extends GenericEntity {
@Temporal(TemporalType.TIMESTAMP)
private Calendar printTime;
@Column(name = "barcode")
private String barcode;
@Column(name = "card_enabled", nullable = false)
private boolean enabled = true;
@Column(name = "rfid_uid")
private String rfidUid;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "printedCard")
private List<ReaderEvent> readerEvents = new ArrayList<ReaderEvent>();
@OneToMany(cascade = CascadeType.ALL, mappedBy = "printedCard")
private List<CardCode> cardCodes = new ArrayList<CardCode>();
@Column(name = "print_count", nullable = false)
private int printCount = 0;
......@@ -112,13 +112,6 @@ public class PrintedCard extends GenericEntity {
this.printTime = printTime;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public boolean getEnabled() {
return enabled;
......@@ -128,14 +121,6 @@ public class PrintedCard extends GenericEntity {
this.enabled = cardEnabled;
}
public String getRfidUid() {
return rfidUid;
}
public void setRfidUid(String rfidUid) {
this.rfidUid = rfidUid;
}
public List<ReaderEvent> getReaderEvents() {
return readerEvents;
}
......@@ -152,6 +137,17 @@ public class PrintedCard extends GenericEntity {
this.currentLocation = currentLocation;
}
public List<CardCode> getCardCodes() {
return cardCodes;
}
public void setCardCodes(List<CardCode> cardCodes) {
this.cardCodes = cardCodes;
}
public EventUser getUser() {
return user;
}
......@@ -176,33 +172,6 @@ public class PrintedCard extends GenericEntity {
return printCount;
}
public static final Comparator<PrintedCard> GAMEPOINT_COMPARATOR = new Comparator<PrintedCard>() {
@Override
public int compare(PrintedCard o1, PrintedCard o2) {
int ret = o2.getGamepoints().compareTo(o1.getGamepoints());
if (ret == 0 && o1.getUser().getUser().getNick() != null && o2.getUser().getUser().getNick() != null)
{
ret = o1.getUser().getUser().getNick().compareTo(o2.getUser().getUser().getNick());
}
return ret;
}
};
@Transient
private Integer gamepoints = null;
public Integer getGamepoints() {
if (gamepoints == null) {
Integer ret = 0;
for (ReaderEvent re : this.getReaderEvents()) {
ret += re.getGamePoint();
}
gamepoints = ret;
}
return gamepoints;
}
public CardState getCardState() {
return cardState;
......@@ -212,21 +181,4 @@ public class PrintedCard extends GenericEntity {
this.cardState = cardState;
}
@Transient
private transient ListDataModel<ReaderEvent> revents;
public ListDataModel<ReaderEvent> getGameCards() {
if (revents == null) {
List<ReaderEvent> ev = this.getReaderEvents();
ArrayList<ReaderEvent> ret = new ArrayList<ReaderEvent>();
for (ReaderEvent e : ev) {
if (e.getGamePoint() > 0) {
ret.add(e);
}
}
revents = new ListDataModel<ReaderEvent>(ret);
}
return revents;
}
}
package fi.codecrew.moya.model;
import java.util.Calendar;
import java.beans.Transient;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
......@@ -40,27 +42,95 @@ public class ReaderEvent extends GenericEntity {
@Column(name = "notes")
private String notes;
@Column(nullable = false)
private Integer gamePoint = 0;
@JoinColumn(name = "printed_cards_id", referencedColumnName = "id", nullable = true, updatable = false)
@ManyToOne(optional = false)
@ManyToOne()
private PrintedCard printedCard;
@JoinColumn(name = "readers_id", referencedColumnName = "id", nullable = false, updatable = false)
@ManyToOne(optional = false)
private Reader reader;
public ReaderEvent(Calendar eventTime, PrintedCard card, Reader reader) {
this.time = eventTime.getTime();
this.printedCard = card;
@JoinColumn(name = "event_users_id", referencedColumnName = "id", nullable = true, updatable = false)
@ManyToOne()
private EventUser user;
@JoinColumn(name = "places_id", referencedColumnName = "id", nullable = true, updatable = false)
@ManyToOne()
private Place place;
@JoinColumn(name = "products_id", referencedColumnName = "id", nullable = true, updatable = false)
@ManyToOne()
private Product product;
@Enumerated(EnumType.STRING)
private ReaderEventType type;
public ReaderEvent(Date eventTime, Reader reader, String value) {
this(eventTime, reader, value, null, null, null, null, ReaderEventType.UNKNOWN);
}
public ReaderEvent(Date eventTime, Reader reader, String value, ReaderEventType type) {
this(eventTime, reader, value, null, null, null, null, type);
}
public ReaderEvent(Date eventTime, Reader reader, String value, PrintedCard card, EventUser user, Place place, Product product, ReaderEventType type) {
this.time = eventTime;
this.reader = reader;
this.value = value;
this.user = user;
this.printedCard = card;
this.user = user;
this.place = place;
this.product = product;
if (type == null)
type = ReaderEventType.UNKNOWN;
this.type = type;
}
public ReaderEvent() {
super();
}
public EventUser getUser() {
return user;
}
public void setUser(EventUser user) {
this.user = user;
}
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public ReaderEventType getType() {
return type;
}
public void setType(ReaderEventType type) {
this.type = type;
}
public String getNotes() {
return notes;
}
......@@ -101,15 +171,10 @@ public class ReaderEvent extends GenericEntity {
this.reader = readersId;
}
public void setGamePoint(Integer gamePoint) {
this.gamePoint = gamePoint;
}
public Integer getGamePoint() {
return gamePoint;
}
public Date getUpdatetime() {
if (updatetime == null)
return time;
return updatetime;
}
......@@ -117,27 +182,24 @@ public class ReaderEvent extends GenericEntity {
this.updatetime = updatetime;
}
@Transient
public String getSeenSince() {
Date comptime = updatetime;
if (comptime == null)
{
comptime = time;
}
long diffSec = (new Date().getTime() - comptime.getTime()) / 1000;
long secs = diffSec % 60;
long diffMin = diffSec / 60;
long mins = diffMin % 60;
long hours = diffMin / 60;
StringBuilder ret = new StringBuilder();
if (hours > 0) {
ret.append(hours).append(" h ");
}
if (hours > 0 || mins > 0) {
ret.append(mins).append(" min ");
}
ret.append(secs).append(" sec");
return ret.toString();
return "" + ((getUpdatetime().getTime() / 1000) / 60) +" min." ;
}
}
package fi.codecrew.moya.model;
public enum ReaderEventType {
USER,
PLACE,
CARD,
PRODUCT,
UNKNOWN
}
......@@ -14,7 +14,6 @@ import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
......@@ -409,4 +408,10 @@ public class User extends GenericEntity implements IUser {
return age;
}
public String getShortUserDescriptor() {
StringBuilder sb = new StringBuilder();
sb.append(getNick()).append(" // ").append(getWholeName()).append(" // ").append(getEmail());
return sb.toString();
}
}
......@@ -32,6 +32,12 @@
<id>iudex</id>
<url>http://iudex.fi/maven/</url>
</repository>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
......@@ -47,7 +53,7 @@
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
<version>5.0.RC2</version>
</dependency>
......
......@@ -3,15 +3,6 @@
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/WebContent" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src"/>
<dependent-module archiveName="moya-beans-client-0.2.0.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/MoyaBeansClient/MoyaBeansClient">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module archiveName="moya-database-0.2.0.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/MoyaDatabase/MoyaDatabase">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module archiveName="moya-utils-0.2.0.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/MoyaUtilities/MoyaUtilities">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="java-output-path" value="/MoyaTerminalWeb/build/classes"/>
<property name="context-root" value="moya-terminal-web"/>
</wb-module>
......
<root>
<facet id="jst.jsf">
<node name="libprov">
<attribute name="provider-id" value="jsf-no-op-library-provider"/>
<attribute name="provider-id" value="GlassFish-4-SystemLibrary-JSF"/>
</node>
</facet>
<facet id="jst.jaxrs">
......
......@@ -2,11 +2,9 @@
<faceted-project>
<runtime name="GlassFish 4.0"/>
<fixed facet="wst.jsdt.web"/>
<fixed facet="jst.web"/>
<fixed facet="java"/>
<installed facet="jst.web" version="3.0"/>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="java" version="1.7"/>
<installed facet="jst.jsf" version="2.0"/>
<installed facet="jst.jsf" version="2.2"/>
<installed facet="jst.web" version="3.1"/>
<installed facet="jst.jaxrs" version="2.0"/>
</faceted-project>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>MoyaTerminalWeb</display-name>
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsf</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
......@@ -19,12 +19,10 @@
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
......@@ -33,25 +31,10 @@
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<!--
<filter>
<display-name>PrimefacesFileupload</display-name>
<filter-name>PrimefacesFileupload</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimefacesFileupload</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
-->
<login-config>
<auth-method>CLIENT-CERT</auth-method>
<realm-name>certificate</realm-name>
</login-config>
<security-constraint>
<display-name>Forbidden resource</display-name>
<web-resource-collection>
......@@ -68,7 +51,6 @@
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<security-constraint>
<display-name>Resource that needs cert auth</display-name>
<web-resource-collection>
......@@ -82,24 +64,6 @@
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<!--
<security-constraint>
<display-name>Resource that needs cert auth</display-name>
<web-resource-collection>
<web-resource-name>BortalTerminalWebResource</web-resource-name>
<url-pattern>/faces/*</url-pattern>
<url-pattern>*.jsf</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>TERMINAL</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint> -->
<persistence-unit-ref>
<persistence-unit-ref-name>BortalEMF</persistence-unit-ref-name>
</persistence-unit-ref>
......
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>fi.codecrew.moya</groupId>
<artifactId>moya-terminal-web</artifactId>
......@@ -25,14 +26,27 @@
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
<packagingIncludes>WEB-INF/lib/javamelody-core*,WEB-INF/lib/primefaces*,**/*.xml,**/*.xhtml,**/*.properties,**/*.class,**/*.png,**/*.css,**/*.js,resources/*</packagingIncludes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>iudex</id>
<url>http://iudex.fi/maven/</url>
</repository>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>fi.codecrew.moya</groupId>
......@@ -47,7 +61,12 @@
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
<version>5.0.RC2</version>
</dependency>
<dependency>
<groupId>net.bull.javamelody</groupId>
<artifactId>javamelody-core</artifactId>
<version>1.46.0</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
......@@ -5,7 +5,8 @@ public enum SpecialPermission {
USER,
ANONYMOUS,
// ORGANISATION_ADMIN,
VERKKOMAKSU_CHECKER
VERKKOMAKSU_CHECKER,
REST
;
public static final String S_USER = "USER";
......
......@@ -12,6 +12,7 @@ public enum UserPermission implements IAppPermission {
READ_ROLES, // ("View all roles."),
WRITE_ROLES, // ("Modify roles"),
VIEW_ACCOUNTEVENTS, // ("Show other users account events"),
VIEW_OWN_ACCOUNTEVENTS, // ("Show other users account events"),
MODIFY_ACCOUNTEVENTS, // ("Modify Account events"),
ANYUSER, // ("All users have this anyways"),
MANAGE_HTTP_SESSION, // ("Manage http sessions"),
......@@ -32,6 +33,7 @@ public enum UserPermission implements IAppPermission {
public static final String S_READ_ROLES = "USER/READ_ROLES";
public static final String S_WRITE_ROLES = "USER/WRITE_ROLES";
public static final String S_VIEW_ACCOUNTEVENTS = "USER/VIEW_ACCOUNTEVENTS";
public static final String S_VIEW_OWN_ACCOUNTEVENTS = "USER/VIEW_OWN_ACCOUNTEVENTS";
public static final String S_MODIFY_ACCOUNTEVENTS = "USER/MODIFY_ACCOUNTEVENTS";
public static final String S_ANYUSER = "USER/ANYUSER";
public static final String S_MANAGE_HTTP_SESSION = "USER/MANAGE_HTTP_SESSION";
......
package fi.codecrew.moya.utilities;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Copyright Iudex / Tuomas Riihimäki
*
*/
public class ByteUtils {
public static int parseUnsigned(byte... b) {
if (b.length > 4) {
throw new RuntimeException("Integer should never have more than 4 bytes!");
}
return new BigInteger(1, b).intValue();
}
public static Long parseUnsignedLong(byte[] b) {
if (b.length > 8) {
throw new RuntimeException("Long should never have more than 4 bytes!");
}
return new BigInteger(1, b).longValue();
}
public static short parseSigned(byte b0, byte b1) {
return (short) (((b0 & 0xff) << 8) | (b1 & 0xff));
}
public static Integer parseSignedO(byte b, byte c) {
return Integer.valueOf(parseSigned(b, c));
}
public static Integer parseSigned(byte b1, byte b2, byte b3, byte b4) {
return (b1 & 0xff) << 24 | (b2 & 0xff) << 16 | (b3 & 0xff) << 8 | (b4 & 0xff);
}
public static void main(String[] ads)
{
System.out.println(parseUnsigned((byte) 0x31, (byte) 0x79));
// System.out.println(parseSignedDecimal("+5.123"));
// System.out.println(parseSignedDecimal("-5.123"));
// System.out.println(parseSignedDecimal(" - 5123"));
// System.out.println(parseSignedDecimal(null));
// System.out.println(parseSignedDecimal(""));
// System.out.println(parseSignedDecimal(" "));
}
public static BigDecimal parseSignedDecimal(String number) {
if (number == null || (number = number.trim()).isEmpty()) {
return null;
}
number = number.trim();
char firstChar = number.charAt(0);
boolean signPositive = true;
switch (firstChar) {
case '-':
signPositive = false;
case '+':
number = number.substring(1).trim();
}
BigDecimal ret = new BigDecimal(number);
if (!signPositive) {
ret = ret.negate();
}
return ret;
}
// public static int parseSignedInt(byte... b) {
// if (b.length > 4) {
// throw new
// RuntimeException("Integer should never have more than 4 bytes!");
// }
// // return new BigInteger(1, b).intValue();
//
// int value = (b[b.length - 1] & 0xff);
// if (b.length > 1) {
// value |= (b[b.length - 2] & 0xff) << 8;
// }
// if (b.length > 2) {
// value |= (b[b.length - 3] & 0xff) << 16;
// }
// if (b.length > 3) {
// value |= (b[b.length - 4] & 0xff) << 24;
// }
// return value;
// }
/**
* Copies the integer value to four bytes in the destination bytearray beginning from the offset
*
* Notice! This function handles signed integers: -1 -> 0xff 0xff 0xff 0xff
*
* @param dst
* @param offset
* @param value
*/
public static void intToBytearray(byte[] dst, int offset, int value) {
dst[offset++] = (byte) (value >>> 24);
dst[offset++] = (byte) (value >>> 16);
dst[offset++] = (byte) (value >>> 8);
dst[offset] = (byte) (value);
}
public static byte[] toArray(int... bytes) {
byte[] ret = new byte[bytes.length];
for (int i = 0; i < bytes.length; ++i) {
ret[i] = (byte) (bytes[i]);
}
return ret;
}
public static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
int val = ((int) b) & 0xff;
if (val < 0x10)
sb.append("0");
sb.append(Integer.toHexString(val));
}
return sb.toString();
}
}
......@@ -66,11 +66,11 @@ public class JpegReader {
return null;
}
public void checkAdobeMarker(File file) throws IOException, ImageReadException {
JpegImageParser parser = new JpegImageParser();
ByteSource byteSource = new ByteSourceFile(file);
@SuppressWarnings("rawtypes")
List<Segment> segments = parser.readSegments(byteSource, new int[] { 0xffee }, true);
if (segments != null && segments.size() >= 1) {
UnknownSegment app14Segment = (UnknownSegment) segments.get(0);
......
package fi.codecrew.moya.utilities;
import java.security.MessageDigest;
public class MD4Digest extends MessageDigest {
/**
* The size in bytes of the input block to the tranformation algorithm.
*/
private static final int BLOCK_LENGTH = 64; // = 512 / 8;
/**
* 4 32-bit words (interim result)
*/
private int[] context = new int[4];
/**
* Number of bytes processed so far mod. 2 power of 64.
*/
private long count;
/**
* 512 bits input buffer = 16 x 32-bit words holds until reaches 512 bits.
*/
private byte[] buffer = new byte[BLOCK_LENGTH];
/**
* 512 bits work buffer = 16 x 32-bit words
*/
private int[] X = new int[16];
public MD4Digest() {
super("MD4");
engineReset();
}
@Override
public void engineUpdate(byte b) {
int i = (int) (count % BLOCK_LENGTH);
count++;
buffer[i] = b;
if (i == BLOCK_LENGTH - 1)
transform(buffer, 0);
}
@Override
protected void engineUpdate(byte[] input, int offset, int len) {
// make sure we don't exceed input's allocated size/length
if (offset < 0 || len < 0 || (long) offset + len > input.length)
throw new ArrayIndexOutOfBoundsException();
// compute number of bytes still unhashed; ie. present in buffer
int bufferNdx = (int) (count % BLOCK_LENGTH);
count += len; // update number of bytes
int partLen = BLOCK_LENGTH - bufferNdx;
int i = 0;
if (len >= partLen) {
System.arraycopy(input, offset, buffer, bufferNdx, partLen);
transform(buffer, 0);
for (i = partLen; i + BLOCK_LENGTH - 1 < len; i += BLOCK_LENGTH)
transform(input, offset + i);
bufferNdx = 0;
}
// buffer remaining input
if (i < len)
System.arraycopy(input, offset + i, buffer, bufferNdx, len - i);
}
@Override
protected byte[] engineDigest() {
// pad output to 56 mod 64; as RFC1320 puts it: congruent to 448 mod 512
int bufferNdx = (int) (count % BLOCK_LENGTH);
int padLen = (bufferNdx < 56) ? (56 - bufferNdx) : (120 - bufferNdx);
// padding is alwas binary 1 followed by binary 0s
byte[] tail = new byte[padLen + 8];
tail[0] = (byte) 0x80;
// append length before final transform:
// save number of bits, casting the long to an array of 8 bytes
// save low-order byte first.
for (int i = 0; i < 8; i++)
tail[padLen + i] = (byte) ((count * 8) >>> (8 * i));
engineUpdate(tail, 0, tail.length);
byte[] result = new byte[16];
// cast this MD4's context (array of 4 ints) into an array of 16 bytes.
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
result[i * 4 + j] = (byte) (context[i] >>> (8 * j));
// reset the engine
engineReset();
return result;
}
@Override
protected void engineReset() {
// initial values of MD4 i.e. A, B, C, D
// as per rfc-1320; they are low-order byte first
context[0] = 0x67452301;
context[1] = 0xEFCDAB89;
context[2] = 0x98BADCFE;
context[3] = 0x10325476;
count = 0L;
for (int i = 0; i < BLOCK_LENGTH; i++)
buffer[i] = 0;
}
/**
* MD4 basic transformation.
* <p>
* Transforms context based on 512 bits from input block starting from the offset'th byte.
*
* @param block
* input sub-array.
* @param offset
* starting position of sub-array.
*/
private void transform(byte[] block, int offset) {
// encodes 64 bytes from input block into an array of 16 32-bit
// entities. Use A as a temp var.
for (int i = 0; i < 16; i++)
X[i] = (block[offset++] & 0xFF) |
(block[offset++] & 0xFF) << 8 |
(block[offset++] & 0xFF) << 16 |
(block[offset++] & 0xFF) << 24;
int A = context[0];
int B = context[1];
int C = context[2];
int D = context[3];
A = FF(A, B, C, D, X[0], 3);
D = FF(D, A, B, C, X[1], 7);
C = FF(C, D, A, B, X[2], 11);
B = FF(B, C, D, A, X[3], 19);
A = FF(A, B, C, D, X[4], 3);
D = FF(D, A, B, C, X[5], 7);
C = FF(C, D, A, B, X[6], 11);
B = FF(B, C, D, A, X[7], 19);
A = FF(A, B, C, D, X[8], 3);
D = FF(D, A, B, C, X[9], 7);
C = FF(C, D, A, B, X[10], 11);
B = FF(B, C, D, A, X[11], 19);
A = FF(A, B, C, D, X[12], 3);
D = FF(D, A, B, C, X[13], 7);
C = FF(C, D, A, B, X[14], 11);
B = FF(B, C, D, A, X[15], 19);
A = GG(A, B, C, D, X[0], 3);
D = GG(D, A, B, C, X[4], 5);
C = GG(C, D, A, B, X[8], 9);
B = GG(B, C, D, A, X[12], 13);
A = GG(A, B, C, D, X[1], 3);
D = GG(D, A, B, C, X[5], 5);
C = GG(C, D, A, B, X[9], 9);
B = GG(B, C, D, A, X[13], 13);
A = GG(A, B, C, D, X[2], 3);
D = GG(D, A, B, C, X[6], 5);
C = GG(C, D, A, B, X[10], 9);
B = GG(B, C, D, A, X[14], 13);
A = GG(A, B, C, D, X[3], 3);
D = GG(D, A, B, C, X[7], 5);
C = GG(C, D, A, B, X[11], 9);
B = GG(B, C, D, A, X[15], 13);
A = HH(A, B, C, D, X[0], 3);
D = HH(D, A, B, C, X[8], 9);
C = HH(C, D, A, B, X[4], 11);
B = HH(B, C, D, A, X[12], 15);
A = HH(A, B, C, D, X[2], 3);
D = HH(D, A, B, C, X[10], 9);
C = HH(C, D, A, B, X[6], 11);
B = HH(B, C, D, A, X[14], 15);
A = HH(A, B, C, D, X[1], 3);
D = HH(D, A, B, C, X[9], 9);
C = HH(C, D, A, B, X[5], 11);
B = HH(B, C, D, A, X[13], 15);
A = HH(A, B, C, D, X[3], 3);
D = HH(D, A, B, C, X[11], 9);
C = HH(C, D, A, B, X[7], 11);
B = HH(B, C, D, A, X[15], 15);
context[0] += A;
context[1] += B;
context[2] += C;
context[3] += D;
}
private int FF(int a, int b, int c, int d, int x, int s) {
int t = a + ((b & c) | (~b & d)) + x;
return t << s | t >>> (32 - s);
}
private int GG(int a, int b, int c, int d, int x, int s) {
int t = a + ((b & (c | d)) | (c & d)) + x + 0x5A827999;
return t << s | t >>> (32 - s);
}
private int HH(int a, int b, int c, int d, int x, int s) {
int t = a + (b ^ c ^ d) + x + 0x6ED9EBA1;
return t << s | t >>> (32 - s);
}
}
package fi.codecrew.moya.utilities;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Copyright Iudex / Tuomas Riihimäki
*
*/
public class NTLMFunctions {
private static final Charset UTF16LE_ENCODING = Charset.forName("UTF-16LE");
private static final Logger logger = LoggerFactory.getLogger(NTLMFunctions.class);
public static String getNTHash(String passAttr)
{
StringBuilder pwd = new StringBuilder();
// pwd.append('"');
pwd.append(passAttr);
// pwd.append('"');
String ret = null;
try {
byte pwdBytes[] = pwd.toString().getBytes(UTF16LE_ENCODING);
//MD4 algo = new MD4();
MessageDigest algo = new MD4Digest();
byte[] bytes = algo.digest(pwdBytes);
ret = ByteUtils.toHexString(bytes);
//logger.info("hex: {}", ret);
} finally {
}
return ret;
}
}
package fi.codecrew.moya.utilities;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
......@@ -19,6 +20,44 @@ public class PasswordFunctions {
private static final boolean UGLY_FIX = true;
private static final Charset LATIN1 = Charset.forName("ISO-8859-15");
public static final String calculateSha1(String source)
{
String ret = null;
try {
final MessageDigest algo = MessageDigest.getInstance("SHA");
final byte[] resultByte = algo.digest(source.getBytes(LATIN1));
ret = new String(Hex.encodeHex(resultByte)).toUpperCase();
} catch (NoSuchAlgorithmException e) {
logger.warn("THIS SHOULD NEVER HAPPEN! (SHA1 hashfunction should always exist)", e);
}
return ret;
}
/**
* Returns the SHA1 sum of the @param fields separated by @param separator e
* eg separator = "+" fields {"ONE", "TWO", "THREE"} return value
* ONE+TWO+THREE
*
* @param separator
* @param fields
* @return
*/
public static final String calculateSha1(String separator, String... fields)
{
String str = mkSeparatedString(separator, fields);
String ret = null;
try {
final MessageDigest algo = MessageDigest.getInstance("SHA");
final byte[] resultByte = algo.digest(str.getBytes(LATIN1));
ret = new String(Hex.encodeHex(resultByte)).toUpperCase();
} catch (NoSuchAlgorithmException e) {
logger.warn("THIS SHOULD NEVER HAPPEN! (SHA1 hashfunction should always exist)", e);
}
return ret;
}
/**
* Returns the MD5 sum of the @param fields separated by @param separator e
* eg separator = "+" fields {"ONE", "TWO", "THREE"} return value
......@@ -28,9 +67,13 @@ public class PasswordFunctions {
* @param fields
* @return
*/
public static String calculateMd5(String separator, String... fields)
public static final String calculateMd5(String separator, String... fields)
{
return calculateMd5(mkSeparatedString(separator, fields));
}
public static final String mkSeparatedString(String separator, String... fields)
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String field : fields)
......@@ -42,17 +85,15 @@ public class PasswordFunctions {
}
sb.append(field);
}
logger.info("Calculating md5 from {}", sb.toString());
return calculateMd5(sb.toString());
return sb.toString();
}
public static String calculateMd5(String str)
public static final String calculateMd5(String str)
{
String ret = null;
try {
final MessageDigest algo = MessageDigest.getInstance("MD5");
final byte[] resultByte = algo.digest(str.getBytes());
final byte[] resultByte = algo.digest(str.getBytes(LATIN1));
ret = new String(Hex.encodeHex(resultByte)).toUpperCase();
} catch (NoSuchAlgorithmException e) {
logger.warn("THIS SHOULD NEVER HAPPEN! (md5 hashfunction should always exist)", e);
......
......@@ -4,7 +4,7 @@ import java.io.Serializable;
public class SearchQuery implements Serializable {
public enum QuerySortOrder {
public static enum QuerySortOrder {
UNSORTED, ASCENDING, DESCENDING
}
......@@ -20,12 +20,13 @@ public class SearchQuery implements Serializable {
super();
}
public SearchQuery(int page, int pagesize, String sort, String search, boolean direction) {
public SearchQuery(int page, int pagesize, String sort, String search, QuerySortOrder direction) {
super();
this.page = page;
this.pagesize = pagesize;
this.sort = sort;
this.search = search;
this.sortDirection = direction;
}
public int getPage() {
......@@ -42,13 +43,14 @@ public class SearchQuery implements Serializable {
}
public int getPagesize() {
if (pagesize < 1) {
pagesize = 20;
}
return pagesize;
}
public void setPagesize(int pagesize) {
if (pagesize < 1)
pagesize = 20;
else
this.pagesize = pagesize;
}
......
......@@ -4,14 +4,13 @@ import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
public interface FacadeCallback<C extends ModelInterface> {
// void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Root<C> root,
// List<Predicate> predicates);
void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, From<?, C> root, List<Predicate> predicates);
void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<C> root, List<Predicate> predicates);
}
......@@ -42,6 +42,7 @@
<h:outputLabel for="defaultrole" value="#{i18n['event.defaultRole']}:" />
<h:selectOneMenu id="defaultrole" converter="#{roleConverter}" value="#{eventorgView.event.defaultRole}">
<f:selectItem itemLabel="---" />
<f:selectItems var="role" itemLabel="#{role.name}" value="#{eventorgView.event.roles}" />
</h:selectOneMenu>
<h:message for="defaultrole" />
......@@ -52,7 +53,7 @@
<h2>#{i18n['event.domains.title']}</h2>
<h:form>
<h:form id="newDomainForm">
<h:inputText value="#{eventorgView.newdomain}" />
<h:commandButton action="#{eventorgView.addDomain()}" value="#{i18n['eventdomain.add']}" />
<h:dataTable var="domain" value="#{eventorgView.eventdomains}">
......@@ -69,8 +70,8 @@
</h:form>
<h2>#{i18n['event.properties.title']}</h2>
<h:form>
<h:dataTable var="prop" value="#{eventPropertyView.properties}">
<h:form id="propertyListForm">
<h:dataTable var="prop" id="propertyListTable" value="#{eventPropertyView.properties}">
<h:column>
<f:facet name="header">#{i18n['lanEventProperty.key']}</f:facet>
<h:outputText value="#{prop.key}" />
......@@ -88,24 +89,25 @@
</h:column>
<h:column>
<h:commandButton action="#{eventPropertyView.editProperty}" value="#{i18n['lanEventProperty.editProperty']}">
<!-- <f:ajax render="@all" execute="@form"/> -->
</h:commandButton>
<p:commandButton ajax="false" action="#{eventPropertyView.editProperty}" value="#{i18n['lanEventProperty.editProperty']}" update=":propertyEditForm" />
</h:column>
<h:column>
<p:commandButton ajax="false" action="#{eventPropertyView.deleteProperty}" onclick="return confirm('#{i18n['lanEventProperty.confirmDelete']}')"
value="#{i18n['lanEventProperty.deleteProperty']}" update=":propertyListForm" />
</h:column>
</h:dataTable>
</h:form>
<h:form>
<h:form id="propertyCreateForm">
<h:selectOneMenu id="propval" value="#{eventPropertyView.createKey}">
<f:selectItems value="#{eventPropertyView.availablePropertyKeys}" />
</h:selectOneMenu>
<h:commandButton action="#{eventPropertyView.initPropertyKeyCreate}" value="#{i18n['lanEventProperty.createProperty']}">
<!-- <f:ajax render="@all" execute="@form" /> -->
</h:commandButton>
<p:commandButton ajax="false" action="#{eventPropertyView.initPropertyKeyCreate}" value="#{i18n['lanEventProperty.createProperty']}" update=":propertyCreateForm,:propertyEditForm" />
<h:message for="propval" />
</h:form>
<h:form rendered="#{!empty eventPropertyView.property}" enctype="#{eventPropertyView.property.key.data?'multipart/form-data':''}">
<h:form id="propertyEditForm" rendered="#{!empty eventPropertyView.property}" enctype="#{eventPropertyView.property.key.data?'multipart/form-data':''}">
<h:panelGrid columns="3">
<h:outputLabel for="key" value="#{i18n['lanEventProperty.key']}" />
<h:outputText value="#{eventPropertyView.property.key}" id="key" />
......@@ -133,20 +135,19 @@
<h:message rendered="#{eventPropertyView.property.key.boolean}" for="booleanval" />
<h:outputLabel rendered="#{eventPropertyView.property.key.long}" for="longval" value="#{i18n['lanEventProperty.longValue']}" />
<h:inputText rendered="#{eventPropertyView.property.key.long}" id="longval" value="#{eventPropertyView.property.longValue}" >
<h:inputText rendered="#{eventPropertyView.property.key.long}" id="longval" value="#{eventPropertyView.property.longValue}">
<f:convertNumber type="number" />
</h:inputText>
<h:message rendered="#{eventPropertyView.property.key.long}" for="longval" />
</h:panelGrid>
<h:commandButton action="#{eventPropertyView.saveProperty}" value="#{i18n['lanEventProperty.save']}" />
<p:commandButton ajax="false" action="#{eventPropertyView.saveProperty}" value="#{i18n['lanEventProperty.save']}" update=":propertyEditForm,:propertyListForm" />
</h:form>
<ui:fragment rendered="#{eventPropertyView.privatePropertyPermission}">
<ui:fragment id="privatePropertyEditor" rendered="#{eventPropertyView.privatePropertyPermission}">
<h2>#{i18n['event.privateProperties.title']}</h2>
<h:form>
<h:form id="privPropList">
<h:dataTable var="prop" value="#{eventPropertyView.privateProperties}">
<h:column>
<f:facet name="header">#{i18n['lanEventPrivateProperty.key']}</f:facet>
......@@ -162,9 +163,13 @@
</h:column>
<h:column>
<h:commandButton action="#{eventPropertyView.editPrivateProperty}" value="#{i18n['lanEventPrivateProperty.editProperty']}">
<p:commandButton ajax="false" action="#{eventPropertyView.editPrivateProperty}" value="#{i18n['lanEventPrivateProperty.editProperty']}">
<!-- <f:ajax render="@all" execute="@form"/> -->
</h:commandButton>
</p:commandButton>
</h:column>
<h:column>
<p:commandButton ajax="false" action="#{eventPropertyView.deletePrivateProperty}" onclick="return confirm('#{i18n['lanEventProperty.confirmDelete']}')"
value="#{i18n['lanEventProperty.deleteProperty']}" update="@form" />
</h:column>
</h:dataTable>
</h:form>
......@@ -173,9 +178,8 @@
<h:selectOneMenu id="propval" value="#{eventPropertyView.createPrivateKey}">
<f:selectItems value="#{eventPropertyView.availablePrivatePropertyKeys}" />
</h:selectOneMenu>
<h:commandButton action="#{eventPropertyView.initPrivatePropertyKeyCreate}" value="#{i18n['lanEventPrivateProperty.createProperty']}">
<!-- <f:ajax render="@all" execute="@form" /> -->
</h:commandButton>
<p:commandButton ajax="false" action="#{eventPropertyView.initPrivatePropertyKeyCreate}" value="#{i18n['lanEventPrivateProperty.createProperty']}" update=":privatePropertyEditor" />
<h:message for="propval" />
</h:form>
......@@ -198,7 +202,7 @@
<h:message rendered="#{eventPropertyView.privateProperty.key.date}" for="textval" />
</h:panelGrid>
<h:commandButton action="#{eventPropertyView.savePrivateProperty}" value="#{i18n['lanEventPrivateProperty.save']}" />
<p:commandButton ajax="false" action="#{eventPropertyView.savePrivateProperty}" value="#{i18n['lanEventPrivateProperty.save']}" update=":privatePropertyEditor" />
</h:form>
......
......@@ -12,12 +12,7 @@
</f:metadata>
<ui:define name="content">
<h:outputScript library="primefaces" name="jquery/jquery.js" target="head" />
<h:form>
<p:poll interval="1" listener="#{incomingView.polledRead}" onerror="location.reload();" />
</h:form>
<h:form>
<h1>#{i18n['incomingflow.userdetails']} (RFID-lukija: #{incomingView.readerId})</h1><h:commandButton action="#{incomingView.changeReader}" value="#{i18n['incomingflow.changereader']}" />
</h:form>
<h1>#{i18n['incomingflow.userdetails']}</h1>
<h:panelGrid id="cropper" columns="3">
<h:panelGroup>
<user:edit id="usereditor" commitaction="#{incomingView.saveUser()}" commitvalue="#{i18n['user.save']}" camAlwaysOn="true" />
......@@ -32,8 +27,9 @@
</h:form>
</h:panelGroup>
<h:panelGroup>
<h:form >
<p:graphicImage url="/dydata/usercard/#{userView.user.user.id}.png" width="300" /><br />
<h:form>
<p:graphicImage url="/dydata/usercard/#{userView.user.user.id}.png" width="300" />
<br />
<h:commandButton action="#{incomingView.printCard}" value="#{i18n['print']}" /> (status: #{incomingView.printedStatus})
</h:form>
</h:panelGroup>
......
......@@ -9,6 +9,7 @@
xmlns:p="http://primefaces.org/ui"
xmlns:shop="http://java.sun.com/jsf/composite/cditools/shop"
xmlns:reader="http://java.sun.com/jsf/composite/cditools/reader"
xmlns:infoview="http://java.sun.com/jsf/composite/cditools/infoview"
xmlns:tools="http://java.sun.com/jsf/composite/cditools">
<h:body>
<ui:composition
......@@ -22,6 +23,11 @@
<f:event type="preRenderView" listener="#{readerList.initReaderList}" />
</f:metadata>
<ui:define name="headercontent">
<infoview:userselector />
</ui:define>
<ui:define name="content">
<h:form>
......@@ -30,18 +36,13 @@
<br />
<br />
<reader:barcode_and_rfid selectvalue="#{i18n['barcodeReader.readBarcode']}" selectaction="#{incomingView.selectUser}" />
<reader:codefield selectvalue="#{i18n['barcodeReader.readBarcode']}" selectaction="#{incomingView.selectUser}" />
<reader:backendReader selectvalue="#{i18n['barcodeReader.readBarcode']}" selectaction="#{incomingView.selectUser}" />
</ui:define>
<ui:define name="sidebar">
<reader:readerlisttiles />
<br />
</ui:define>
</ui:composition>
</h:body>
......
......@@ -83,9 +83,7 @@
</h:link>
</p:column>
<p:column rendered="#{billListView.canWriteBill}">
<h:commandButton rendered="#{bill.paidDate == null and billListView.showPayButtons}" action="#{billListView.markPaid()}" value="#{i18n['bill.markPaid']}">
<f:ajax render="@form" />
</h:commandButton>
<p:commandButton onerror="location.reload(true)" rendered="#{bill.paidDate == null and billListView.showPayButtons}" action="#{billListView.markPaid()}" value="#{i18n['bill.markPaid']}" />
<h:outputText rendered="#{bill.paidDate != null}" value="#{i18n['bill.isPaid']}" />
</p:column>
<p:column rendered="#{!billListView.canWriteBill}">
......
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:tools="http://java.sun.com/jsf/composite/tools" xmlns:p="http://primefaces.org/ui">
<composite:interface>
<composite:attribute name="commitValue" required="true" />
<composite:attribute name="commitAction" method-signature="java.lang.String action()" required="true" />
</composite:interface>
<composite:implementation>
<h:form>
<h:panelGrid columns="3">
<h:outputLabel value="#{i18n['voting.create.name']}:" for="name" />
<h:inputText value="#{compoMgmtView.compo.name}" id="name" />
<h:message for="name" />
<h:outputLabel value="#{i18n['voting.create.description']}:" for="desc" />
<h:inputText value="#{compoMgmtView.compo.description}" id="desc" />
<h:message for="desc" />
<h:outputLabel value="#{i18n['voting.create.maxParticipants']}:" for="maxPar" />
<h:inputText value="#{compoMgmtView.compo.maxParticipantCount}" id="maxPar" />
<h:message for="maxPar" />
<h:outputLabel value="#{i18n['voting.create.holdVoting']}:" for="holdVoting" />
<h:selectBooleanCheckbox value="#{compoMgmtView.compo.holdVoting}" id="holdVoting" />
<h:message for="holdVoting" />
<h:outputLabel value="#{i18n['voting.create.hidden']}:" for="hidden" />
<h:selectBooleanCheckbox value="#{compoMgmtView.compo.hidden}" id="hidden" />
<h:message for="hidden" />
<h:outputLabel value="#{i18n['voting.create.compoStart']}:" for="cStart" />
<p:calendar validator="#{votingDateValidator.saveCStart}" value="#{compoMgmtView.compo.startTime}" pattern="dd/MM/yyyy HH:mm" id="cStart" />
<h:message for="cStart" />
<h:outputLabel value="#{i18n['voting.create.compoEnd']}:" for="cEnd" />
<p:calendar validator="#{votingDateValidator.validateCompo}" value="#{compoMgmtView.compo.endTime}" pattern="dd/MM/yyyy HH:mm" id="cEnd" />
<h:message for="cEnd" />
<h:outputLabel value="#{i18n['voting.create.voteStart']}:" for="vStart" />
<p:calendar validator="#{votingDateValidator.saveVStart}" value="#{compoMgmtView.compo.voteStart}" pattern="dd/MM/yyyy HH:mm" id="vStart" />
<h:message for="vStart" />
<h:outputLabel value="#{i18n['voting.create.voteEnd']}:" for="vEnd" />
<p:calendar validator="#{votingDateValidator.validateVote}" value="#{compoMgmtView.compo.voteEnd}" pattern="dd/MM/yyyy HH:mm" id="vEnd" />
<h:message for="vEnd" />
<h:outputLabel value="#{i18n['voting.create.submitStart']}:" for="sStart" />
<p:calendar validator="#{votingDateValidator.saveSStart}" value="#{compoMgmtView.compo.submitStart}" pattern="dd/MM/yyyy HH:mm" id="sStart" />
<h:message for="sStart" />
<h:outputLabel value="#{i18n['voting.create.submitEnd']}:" for="sEnd" />
<p:calendar validator="#{votingDateValidator.validateSubmit}" value="#{compoMgmtView.compo.submitEnd}" pattern="dd/MM/yyyy HH:mm" id="sEnd" />
<h:message for="sEnd" />
<h:commandButton action="#{cc.attrs.commitAction}" id="commitbutton" value="#{cc.attrs.commitValue}" />
</h:panelGrid>
</h:form>
</composite:implementation>
</html>
......@@ -78,7 +78,7 @@
<f:ajax render="@form" />
</h:commandButton>
<h:inputText size="4" id="cartcount" value="#{cart.count}">
<f:convertNumber maxIntegerDigits="2" minFractionDigits="0" />
<f:convertNumber maxFractionDigits="2" minFractionDigits="0" />
</h:inputText>
<h:commandButton action="#{foodWaveFoodView.addOne}"
value="#{i18n['productshop.plusOne']}">
......
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui"
xmlns:reader="http://java.sun.com/jsf/composite/cditools/reader"
>
<composite:interface>
</composite:interface>
<composite:implementation>
<reader:backendReader />
</composite:implementation>
</html>
\ No newline at end of file
......@@ -40,24 +40,24 @@
<h:commandButton action="#{productShopView.addMinusOne}" value="#{i18n['productshop.minusOne']}">
<f:ajax render="@form" />
</h:commandButton>
<h:outputText id="cartcount" escape="false" value="&nbsp;&nbsp;#{cart.count}&nbsp;&nbsp;">
<f:convertNumber maxIntegerDigits="2" minFractionDigits="0" />
</h:outputText>
<p:inputText size="2" id="cartcount" escape="false" value="#{cart.count}">
<f:ajax render="@form" listener="#{productShopView.countChangeListener}" />
<f:convertNumber maxFractionDigits="2" minFractionDigits="0" />
</p:inputText>
<h:commandButton action="#{productShopView.addOne}" value="#{i18n['productshop.plusOne']}">
<f:ajax render="@form" />
</h:commandButton>
</p:column>
<p:column rendered="#{productShopView.hasLimits}">
<f:facet name="header">
<h:outputText value="#{i18n['productshop.limits']}" />
</f:facet>
<h:outputText value="#{cart.limit}">
<f:convertNumber maxIntegerDigits="2" minFractionDigits="0" />
<f:convertNumber maxFractionDigits="2" minFractionDigits="0" />
</h:outputText>
</p:column>
<p:column>
<h:dataTable border="0" var="disc" value="#{cart.discounts}">
<h:dataTable styleClass="noborderTable" border="0" var="disc" value="#{cart.discounts}">
<p:column>
<h:outputText value="#{disc.shortdesc}" />
</p:column>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!