Commit fa09aba0 by Tuukka Kivilahti

Merge remote-tracking branch 'origin/deploy-2018-07-27' into feature/folderStructure

2 parents 4f41f41a bf475dd2
Showing with 3190 additions and 782 deletions
...@@ -2,6 +2,7 @@ package fi.codecrew.moya.beans; ...@@ -2,6 +2,7 @@ package fi.codecrew.moya.beans;
import fi.codecrew.moya.model.Allergy; import fi.codecrew.moya.model.Allergy;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.UsersAllergy; import fi.codecrew.moya.model.UsersAllergy;
import javax.ejb.Local; import javax.ejb.Local;
...@@ -13,6 +14,7 @@ public interface AllergyBeanLocal { ...@@ -13,6 +14,7 @@ public interface AllergyBeanLocal {
List<Allergy> getAllergies(); List<Allergy> getAllergies();
List<UsersAllergy> getUserAllergies(User currentUser);
List<UsersAllergy> getUserAllergies(EventUser currentUser); List<UsersAllergy> getUserAllergies(EventUser currentUser);
List<UsersAllergy> saveAllergies(ArrayList<UsersAllergy> allergylist); List<UsersAllergy> saveAllergies(ArrayList<UsersAllergy> allergylist);
......
...@@ -37,4 +37,14 @@ public interface ApiApplicationBeanLocal { ...@@ -37,4 +37,14 @@ public interface ApiApplicationBeanLocal {
ApiApplication findApplication(String appKey); ApiApplication findApplication(String appKey);
String findUsernameForApikey(String appkey, String userkey, String domain); String findUsernameForApikey(String appkey, String userkey, String domain);
ApiApplication createApiApplication(ApiApplication apiApp);
ApiApplication findApplication(Integer id);
ApiApplication saveApiApplication(ApiApplication apiApp);
List<ApiApplicationInstance> findInstances(ApiApplication apiApp);
ApiApplicationInstance saveApiInstance(ApiApplicationInstance selectedInstance);
} }
...@@ -24,6 +24,7 @@ import javax.resource.spi.IllegalStateException; ...@@ -24,6 +24,7 @@ import javax.resource.spi.IllegalStateException;
import fi.codecrew.moya.enums.apps.IAppPermission; import fi.codecrew.moya.enums.apps.IAppPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission; import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.model.User; import fi.codecrew.moya.model.User;
@Local @Local
...@@ -61,6 +62,7 @@ public interface PermissionBeanLocal { ...@@ -61,6 +62,7 @@ public interface PermissionBeanLocal {
String getPrincipalName(); String getPrincipalName();
// boolean hasPermission(String perm); // boolean hasPermission(String perm);
} }
...@@ -22,6 +22,7 @@ import java.io.IOException; ...@@ -22,6 +22,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.List; import java.util.List;
import java.util.Map;
import javax.ejb.Local; import javax.ejb.Local;
...@@ -146,6 +147,8 @@ public interface UserBeanLocal { ...@@ -146,6 +147,8 @@ public interface UserBeanLocal {
boolean isUserInRole(EventUser user, Integer roleId); boolean isUserInRole(EventUser user, Integer roleId);
boolean isUserInRole(EventUser user, Role role);
EventUser getOtherEventsEventuser(User user, LanEvent event); EventUser getOtherEventsEventuser(User user, LanEvent event);
/** /**
...@@ -208,4 +211,15 @@ public interface UserBeanLocal { ...@@ -208,4 +211,15 @@ public interface UserBeanLocal {
* @return EventUser with the matching code * @return EventUser with the matching code
*/ */
EventUser findUserByCodeToken(String code); EventUser findUserByCodeToken(String code);
/**
* Return eventusers of all events for user
* This function can only be used by users themselves, and superadmins.
* @param user User to fetch eventusers for
* @return Eventusers for all events this user has been associated to.
*/
List<EventUser> findAllEventusers(User user);
Map<Role,List<String>> findUsersRolesWithReason(EventUser user);
} }
package fi.codecrew.moya.beans;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUserproperty;
import fi.codecrew.moya.model.UsersEventUserproperty;
import javax.ejb.Local;
import java.util.List;
@Local
public interface UserPropertyBeanLocal {
List<EventUserproperty> getPropertiesForUser(EventUser user);
List<UsersEventUserproperty> getUserPropertiesForUser(EventUser user);
UsersEventUserproperty saveUserproperty(UsersEventUserproperty object);
}
...@@ -22,10 +22,7 @@ import java.util.List; ...@@ -22,10 +22,7 @@ import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import fi.codecrew.moya.model.Compo; import fi.codecrew.moya.model.*;
import fi.codecrew.moya.model.CompoEntry;
import fi.codecrew.moya.model.CompoEntryFile;
import fi.codecrew.moya.model.Vote;
@Local @Local
public interface VotingBeanLocal { public interface VotingBeanLocal {
...@@ -59,4 +56,9 @@ public interface VotingBeanLocal { ...@@ -59,4 +56,9 @@ public interface VotingBeanLocal {
public List<CompoEntry> getEntriesForCurrentUser(); public List<CompoEntry> getEntriesForCurrentUser();
Compo saveFiletype(CompoFileType filetype);
Compo deleteFiletype(CompoFileType ft);
CompoEntryFileType findEntryFileType(Integer entryId, Integer typeId);
} }
...@@ -4,6 +4,7 @@ import fi.codecrew.moya.facade.AllergyFacade; ...@@ -4,6 +4,7 @@ import fi.codecrew.moya.facade.AllergyFacade;
import fi.codecrew.moya.facade.UsersAllergyFacade; import fi.codecrew.moya.facade.UsersAllergyFacade;
import fi.codecrew.moya.model.Allergy; import fi.codecrew.moya.model.Allergy;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.UsersAllergy; import fi.codecrew.moya.model.UsersAllergy;
import javax.ejb.EJB; import javax.ejb.EJB;
...@@ -27,11 +28,16 @@ public class AllergyBean implements AllergyBeanLocal { ...@@ -27,11 +28,16 @@ public class AllergyBean implements AllergyBeanLocal {
} }
@Override @Override
public List<UsersAllergy> getUserAllergies(EventUser user) { public List<UsersAllergy> getUserAllergies(User user) {
return userAllergyFacade.findForUser(user); return userAllergyFacade.findForUser(user);
} }
@Override @Override
public List<UsersAllergy> getUserAllergies(EventUser user) {
return userAllergyFacade.findForUser(user.getUser());
}
@Override
public List<UsersAllergy> saveAllergies(ArrayList<UsersAllergy> allergylist) { public List<UsersAllergy> saveAllergies(ArrayList<UsersAllergy> allergylist) {
ArrayList<UsersAllergy> ret = new ArrayList<>(); ArrayList<UsersAllergy> ret = new ArrayList<>();
for (UsersAllergy a : allergylist) { for (UsersAllergy a : allergylist) {
......
...@@ -24,10 +24,8 @@ import java.util.List; ...@@ -24,10 +24,8 @@ import java.util.List;
import javax.annotation.security.DeclareRoles; import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed; import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB; import javax.ejb.*;
import javax.ejb.EJBException; import javax.security.jacc.EJBMethodPermission;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;
import fi.codecrew.moya.enums.apps.SpecialPermission; import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.facade.ApiApplicationFacade; import fi.codecrew.moya.facade.ApiApplicationFacade;
...@@ -47,7 +45,7 @@ import org.slf4j.LoggerFactory; ...@@ -47,7 +45,7 @@ import org.slf4j.LoggerFactory;
*/ */
@Singleton @Singleton
@LocalBean @LocalBean
@DeclareRoles(SpecialPermission.S_SUPERADMIN) @DeclareRoles({SpecialPermission.S_SUPERADMIN, SpecialPermission.S_USER})
public class ApiApplicationBean implements ApiApplicationBeanLocal { public class ApiApplicationBean implements ApiApplicationBeanLocal {
@EJB @EJB
...@@ -71,6 +69,7 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal { ...@@ -71,6 +69,7 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal {
UserBean userBean; UserBean userBean;
private static final Logger logger = LoggerFactory.getLogger(ApiApplicationBean.class); private static final Logger logger = LoggerFactory.getLogger(ApiApplicationBean.class);
/** /**
* Default constructor. * Default constructor.
*/ */
...@@ -142,6 +141,69 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal { ...@@ -142,6 +141,69 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal {
@Override @Override
@RolesAllowed(SpecialPermission.S_USER) @RolesAllowed(SpecialPermission.S_USER)
public ApiApplication createApiApplication(ApiApplication apiApp) {
if (apiApp.getDeveloper() == null) {
apiApp.setDeveloper(permissionBean.getCurrentUser().getUser());
}
if (apiApp.getApplicationKey() == null || apiApp.getApplicationKey().isEmpty()) {
apiApp.setApplicationKey(PasswordFunctions.generateRandomString(20, PasswordFunctions.ALL_CHARS));
}
if (apiApp.getApplicationKey().length() < 8) {
throw new EJBException("Application key musst be at least 8 characters long");
}
if (!permissionBean.hasPermission(SpecialPermission.SUPERADMIN) && !permissionBean.isCurrentUser(apiApp.getDeveloper())) {
throw new EJBAccessException("Trying to create application for different user");
}
apiApp.setCreated(new Date());
applicationFacade.create(apiApp);
return apiApp;
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
public ApiApplication findApplication(Integer id) {
ApiApplication ret = applicationFacade.find(id);
if (!permissionBean.isCurrentUser(ret.getDeveloper()) && !permissionBean.hasPermission(SpecialPermission.SUPERADMIN)) {
throw new EJBAccessException("Trying to return apiapp for wrong user");
}
return ret;
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
public ApiApplication saveApiApplication(ApiApplication apiApp) {
if (!permissionBean.isCurrentUser(apiApp.getDeveloper()) && permissionBean.hasPermission(SpecialPermission.SUPERADMIN)) {
throw new EJBAccessException("Trying to save apiapp for another user");
}
return applicationFacade.merge(apiApp);
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
public List<ApiApplicationInstance> findInstances(ApiApplication apiApp) {
return instanceFacade.findForUser(permissionBean.getCurrentUser(), apiApp);
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
public ApiApplicationInstance saveApiInstance(ApiApplicationInstance instance) {
if (instance.getEventuser() == null) {
instance.setEventuser(permissionBean.getCurrentUser());
}
if (!permissionBean.isCurrentUser(instance.getEventuser()) && !permissionBean.hasPermission(SpecialPermission.SUPERADMIN)) {
throw new EJBAccessException("Trying to create apiInstance to foreign user");
}
if (instance.getId() == null) {
instanceFacade.create(instance);
return instance;
}
return instanceFacade.merge(instance);
}
@Override
@RolesAllowed(SpecialPermission.S_USER)
public List<ApiApplication> findMyApplications() { public List<ApiApplication> findMyApplications() {
EventUser curruser = permissionBean.getCurrentUser(); EventUser curruser = permissionBean.getCurrentUser();
return applicationFacade.findForUser(curruser); return applicationFacade.findForUser(curruser);
...@@ -153,4 +215,5 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal { ...@@ -153,4 +215,5 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal {
return applicationFacade.findAll(); return applicationFacade.findAll();
} }
} }
...@@ -586,8 +586,49 @@ public class BootstrapBean implements BootstrapBeanLocal { ...@@ -586,8 +586,49 @@ public class BootstrapBean implements BootstrapBeanLocal {
"ALTER TABLE users ALTER confirm_time TYPE TIMESTAMPTZ", "ALTER TABLE users ALTER confirm_time TYPE TIMESTAMPTZ",
"ALTER TABLE users ALTER created TYPE TIMESTAMPTZ" "ALTER TABLE users ALTER created TYPE TIMESTAMPTZ"
}); });
dbUpdates.add(new String[]{
"CREATE TABLE event_userproperties (id SERIAL NOT NULL, description jsonb not null, meta json, name jsonb not null, TYPE TEXT NOT NULL, event_id INTEGER NOT NULL, for_role_id INTEGER, PRIMARY KEY (id))",
"CREATE TABLE users_event_userproperties (id SERIAL NOT NULL, datavalue BYTEA, decimalvalue DECIMAL(38,10), integervalue BIGINT, meta json, textvalue TEXT, property_id INTEGER NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (id))",
"ALTER TABLE event_userproperties ADD CONSTRAINT FK_event_userproperties_for_role_id FOREIGN KEY (for_role_id) REFERENCES roles (id)",
"ALTER TABLE event_userproperties ADD CONSTRAINT FK_event_userproperties_event_id FOREIGN KEY (event_id) REFERENCES events (id)",
"ALTER TABLE users_event_userproperties ADD CONSTRAINT FK_users_event_userproperties_property_id FOREIGN KEY (property_id) REFERENCES event_userproperties (id)",
"ALTER TABLE users_event_userproperties ADD CONSTRAINT FK_users_event_userproperties_user_id FOREIGN KEY (user_id) REFERENCES event_users (id)"
});
dbUpdates.add(new String[]{
"ALTER TABLE compo_entry_files ADD COLUMN type_id INTEGER",
"CREATE TABLE compo_file_types (id SERIAL NOT NULL, description TEXT, filetype TEXT, meta jsonb, name TEXT, required BOOLEAN, SORT INTEGER NOT NULL, compo_id INTEGER NOT NULL, PRIMARY KEY (id))",
"ALTER TABLE compo_entry_files ADD CONSTRAINT FK_compo_entry_files_type_id FOREIGN KEY (type_id) REFERENCES compo_file_types (id)",
"ALTER TABLE compo_file_types ADD CONSTRAINT FK_compo_file_types_compo_id FOREIGN KEY (compo_id) REFERENCES compos (id)"
});
dbUpdates.add(new String[]{
"ALTER TABLE compo_entry_files RENAME TO old_compo_entry_file",
"CREATE TABLE compo_entry_files (id SERIAL NOT NULL, description TEXT, file_name TEXT, filepath TEXT NOT NULL, hash TEXT, meta jsonb, mime_type TEXT, uploaded TIMESTAMPTZ NOT NULL, entryfiletype_id INTEGER NOT NULL, PRIMARY KEY (id))",
"CREATE TABLE compo_entry_file_types (id SERIAL NOT NULL, meta jsonb, updated TIMESTAMPTZ NOT NULL, current_file_id INTEGER, entry_id INTEGER NOT NULL, type_id INTEGER NOT NULL, PRIMARY KEY (id))",
"ALTER TABLE compo_entry_file_types ADD CONSTRAINT UNQ_compo_entry_file_types_0 UNIQUE (entry_id, type_id)",
"ALTER TABLE compo_entry_file_types ADD CONSTRAINT FK_compo_entry_file_types_type_id FOREIGN KEY (type_id) REFERENCES compo_file_types (id)",
"ALTER TABLE compo_entry_file_types ADD CONSTRAINT FK_compo_entry_file_types_current_file_id FOREIGN KEY (current_file_id) REFERENCES compo_entry_files (id)",
"ALTER TABLE compo_entry_file_types ADD CONSTRAINT FK_compo_entry_file_types_entry_id FOREIGN KEY (entry_id) REFERENCES compo_entries (id)",
"ALTER TABLE compo_entry_files ADD CONSTRAINT FK_compo_entry_files_entryfiletype_id FOREIGN KEY (entryfiletype_id) REFERENCES compo_entry_file_types (id)",
});
dbUpdates.add(new String[]{
"CREATE TABLE compo_voting_schemes (id SERIAL NOT NULL, allow_recusal BOOLEAN NOT NULL, max_value DECIMAL(24,8), meta jsonb, min_value DECIMAL(24,8), name TEXT NOT NULL, type TEXT NOT NULL, value_increment DECIMAL(24,8), event_id INTEGER NOT NULL, PRIMARY KEY (id))",
"CREATE TABLE compo_voting_roles (id SERIAL NOT NULL, meta jsonb, multiplier DECIMAL(24,8) NOT NULL, override_max DECIMAL(24,8), override_min DECIMAL(24,8), override_others BOOLEAN NOT NULL, PRIORITY INTEGER NOT NULL, role_id INTEGER NOT NULL, scheme_id INTEGER NOT NULL, PRIMARY KEY (id))",
"ALTER TABLE COMPOS ADD COLUMN entrysubmit_role_id INTEGER, ADD COLUMN voting_scheme_id INTEGER",
"ALTER TABLE compo_voting_schemes ADD CONSTRAINT FK_compo_voting_schemes_event_id FOREIGN KEY (event_id) REFERENCES events (id)",
"ALTER TABLE compos ADD CONSTRAINT FK_compos_voting_scheme_id FOREIGN KEY (voting_scheme_id) REFERENCES compo_voting_schemes (id)",
"ALTER TABLE compo_voting_roles ADD CONSTRAINT UNQ_compo_voting_roles_0 UNIQUE (scheme_id, role_id)",
"ALTER TABLE compo_voting_roles ADD CONSTRAINT FK_compo_voting_roles_scheme_id FOREIGN KEY (scheme_id) REFERENCES compo_voting_schemes (id)",
"ALTER TABLE compo_voting_roles ADD CONSTRAINT FK_compo_voting_roles_role_id FOREIGN KEY (role_id) REFERENCES roles (id)",
});
} }
public BootstrapBean() { public BootstrapBean() {
} }
......
...@@ -28,6 +28,7 @@ import javax.resource.spi.IllegalStateException; ...@@ -28,6 +28,7 @@ import javax.resource.spi.IllegalStateException;
import fi.codecrew.moya.enums.apps.*; import fi.codecrew.moya.enums.apps.*;
import fi.codecrew.moya.facade.EventFacade; import fi.codecrew.moya.facade.EventFacade;
import fi.codecrew.moya.model.LanEvent; import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.Role;
import fi.codecrew.moya.utilities.UserLoginUtils; import fi.codecrew.moya.utilities.UserLoginUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -127,6 +128,8 @@ public class PermissionBean implements PermissionBeanLocal { ...@@ -127,6 +128,8 @@ public class PermissionBean implements PermissionBeanLocal {
@EJB @EJB
private EventBean eventbean; private EventBean eventbean;
@EJB
private UserBean userbean;
@Override @Override
......
...@@ -29,12 +29,7 @@ import java.math.BigDecimal; ...@@ -29,12 +29,7 @@ import java.math.BigDecimal;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.security.DeclareRoles; import javax.annotation.security.DeclareRoles;
import javax.annotation.security.PermitAll; import javax.annotation.security.PermitAll;
...@@ -99,13 +94,13 @@ import fi.codecrew.moya.utilities.moyamessage.MoyaEventType; ...@@ -99,13 +94,13 @@ import fi.codecrew.moya.utilities.moyamessage.MoyaEventType;
@LocalBean @LocalBean
@Stateless @Stateless
@DeclareRoles({ @DeclareRoles({
UserPermission.S_VIEW_ALL, UserPermission.S_VIEW_ALL,
UserPermission.S_CREATE_NEW, UserPermission.S_CREATE_NEW,
UserPermission.S_INVITE_USERS, UserPermission.S_INVITE_USERS,
UserPermission.S_MODIFY, UserPermission.S_MODIFY,
SpecialPermission.S_USER, SpecialPermission.S_USER,
EventPermission.S_MANAGE_EVENT, EventPermission.S_MANAGE_EVENT,
SpecialPermission.S_SUPERADMIN SpecialPermission.S_SUPERADMIN
}) })
public class UserBean implements UserBeanLocal { public class UserBean implements UserBeanLocal {
...@@ -191,7 +186,7 @@ public class UserBean implements UserBeanLocal { ...@@ -191,7 +186,7 @@ public class UserBean implements UserBeanLocal {
@Override @Override
public boolean setUsersLocale(String locale) { public boolean setUsersLocale(String locale) {
if(permbean.getCurrentUser().isAnonymous()) { if (permbean.getCurrentUser().isAnonymous()) {
return false; return false;
} }
...@@ -233,7 +228,16 @@ public class UserBean implements UserBeanLocal { ...@@ -233,7 +228,16 @@ public class UserBean implements UserBeanLocal {
throw new EJBAccessException("Not enough rights to find roles"); throw new EJBAccessException("Not enough rights to find roles");
} }
return new ArrayList<Role>(localFindUsersRoles(u)); ArrayList<Role> ret = new ArrayList<>(localFindUsersRoles(u));
ret.sort((o1, o2) -> o1.getId().compareTo(o2.getId()));
return ret;
}
@Override
@RolesAllowed(UserPermission.S_VIEW_ALL)
public Map<Role, List<String>> findUsersRolesWithReason(EventUser u) {
return localFindUsersRolesWithReason(u);
} }
...@@ -244,6 +248,10 @@ public class UserBean implements UserBeanLocal { ...@@ -244,6 +248,10 @@ public class UserBean implements UserBeanLocal {
// Käytä Viewien puolelta findUsersRoles joka tarkistaa käyttäjän oikeudet // Käytä Viewien puolelta findUsersRoles joka tarkistaa käyttäjän oikeudet
// ensin. // ensin.
public Set<Role> localFindUsersRoles(EventUser u) { public Set<Role> localFindUsersRoles(EventUser u) {
return localFindUsersRolesWithReason(u).keySet();
}
public HashMap<Role, List<String>> localFindUsersRolesWithReason(EventUser u) {
// if (currentEventuser != null && u.equals(currentEventuser)) { // if (currentEventuser != null && u.equals(currentEventuser)) {
// logger.debug("Returnin cached eventuserroles for user {}: {}", // logger.debug("Returnin cached eventuserroles for user {}: {}",
// currentEventuser, currentEventuserRoles); // currentEventuser, currentEventuserRoles);
...@@ -251,26 +259,27 @@ public class UserBean implements UserBeanLocal { ...@@ -251,26 +259,27 @@ public class UserBean implements UserBeanLocal {
// } // }
LanEvent event = u.getEvent(); LanEvent event = u.getEvent();
Set<Role> checkedRoles = new HashSet<Role>(); //Set<Role> checkedRoles = new HashSet<Role>();
HashMap<Role, List<String>> checkedRoles = new HashMap<>();
if (u != null) { if (u != null) {
addRecursive(checkedRoles, rolefacade.findForUser(u)); addRecursive(checkedRoles, rolefacade.findForUser(u), "DIRECT");
addRecursive(checkedRoles, orgRoleFacade.findRolesForUser(u)); addRecursive(checkedRoles, orgRoleFacade.findRolesForUser(u), "ORG_ROLE");
if (permbean.isLoggedIn()) { if (permbean.isLoggedIn()) {
// add roles from events default role. // add roles from events default role.
addRecursive(checkedRoles, event.getDefaultRole()); addRecursive(checkedRoles, event.getDefaultRole(), "EVENT_DEFAULT");
} }
if (!u.isAnonymous()) { if (!u.isAnonymous()) {
// add roles from accountEvents of the user // add roles from accountEvents of the user
addRecursive(checkedRoles, productbean.getRolesFromAccountEvents(u)); addRecursive(checkedRoles, productbean.getRolesFromAccountEvents(u), "ACCOUNTEVENT");
for (GroupMembership member : gmfacade.findMemberships(u)) { for (GroupMembership member : gmfacade.findMemberships(u)) {
if (member != null && member.getPlaceReservation() != null) { if (member != null && member.getPlaceReservation() != null) {
addRecursive(checkedRoles, member.getPlaceReservation().getProvidesRole()); addRecursive(checkedRoles, member.getPlaceReservation().getProvidesRole(), "PLACE");
if (member.getPlaceReservation().getProduct() != null) { if (member.getPlaceReservation().getProduct() != null) {
addRecursive(checkedRoles, member.getPlaceReservation().getProduct().getProvides()); addRecursive(checkedRoles, member.getPlaceReservation().getProduct().getProvides(), "PLACE_PRODUCT");
} }
} }
} }
...@@ -286,20 +295,28 @@ public class UserBean implements UserBeanLocal { ...@@ -286,20 +295,28 @@ public class UserBean implements UserBeanLocal {
return checkedRoles; return checkedRoles;
} }
private void addRecursive(Set<Role> checkedRoles, Collection<Role> roles) { public void addRecursive(Map<Role, List<String>> checkedRoles, Collection<Role> roles, String source) {
for (Role r : roles) { for (Role r : roles) {
addRecursive(checkedRoles, r); addRecursive(checkedRoles, r, source);
} }
} }
private void addRecursive(Set<Role> checkedRoles, Role role) { public void addRecursive(Map<Role, List<String>> checkedRoles, Role role, String source) {
if (role == null || checkedRoles.contains(role)) { if (role == null) {
return; return;
} }
checkedRoles.add(role);
for (Role r : role.getParents()) {
addRecursive(checkedRoles, r); List<String> reasons = checkedRoles.get(role);
if (reasons == null) {
reasons = new ArrayList<>();
checkedRoles.put(role, reasons);
for (Role r : role.getParents()) {
addRecursive(checkedRoles, r, source);
}
} }
reasons.add(source);
} }
...@@ -966,11 +983,11 @@ public class UserBean implements UserBeanLocal { ...@@ -966,11 +983,11 @@ public class UserBean implements UserBeanLocal {
@Override @Override
public boolean isUserInRole(EventUser user, Integer roleId) { public boolean isUserInRole(EventUser user, Integer roleId) {
Set<Role> roles = localFindUsersRoles(user); HashMap<Role, List<String>> roles = localFindUsersRolesWithReason(user);
logger.info("CHecking user {} roleid {} from roles {}, roles size{}", new Object[]{user, roleId, roles, roles.size()}); logger.info("CHecking user {} roleid {} from roles {}, roles size{}", new Object[]{user, roleId, roles, roles.size()});
addRecursive(roles, eventBean.getCurrentEvent().getDefaultRole()); addRecursive(roles, eventBean.getCurrentEvent().getDefaultRole(), "DEFAULT");
for (Role r : roles) { for (Role r : roles.keySet()) {
if (roleId.equals(r.getId())) { if (roleId.equals(r.getId())) {
logger.info("User {} found in role {}", user, roleId); logger.info("User {} found in role {}", user, roleId);
return true; return true;
...@@ -981,6 +998,12 @@ public class UserBean implements UserBeanLocal { ...@@ -981,6 +998,12 @@ public class UserBean implements UserBeanLocal {
} }
@Override @Override
public boolean isUserInRole(EventUser user, Role role) {
return role != null && isUserInRole(user, role.getId());
}
@Override
public User getUser(Integer id) { public User getUser(Integer id) {
User ret = userFacade.find(id); User ret = userFacade.find(id);
...@@ -1046,7 +1069,7 @@ public class UserBean implements UserBeanLocal { ...@@ -1046,7 +1069,7 @@ public class UserBean implements UserBeanLocal {
dstUser.addAccountevent(dstacc); dstUser.addAccountevent(dstacc);
accountEventFacade.create(dstacc); accountEventFacade.create(dstacc);
logger.info("Transferred {} credits with price {} for user {} from {} to {}", logger.info("Transferred {} credits with price {} for user {} from {} to {}",
new Object[]{count, creditPrice, srcUser.getUser(), srcUser, dstUser}); new Object[]{count, creditPrice, srcUser.getUser(), srcUser, dstUser});
dstTotal = dstTotal.add(dstacc.getTotal()); dstTotal = dstTotal.add(dstacc.getTotal());
} }
...@@ -1180,6 +1203,16 @@ public class UserBean implements UserBeanLocal { ...@@ -1180,6 +1203,16 @@ public class UserBean implements UserBeanLocal {
return eventUser; return eventUser;
} }
@Override
@RolesAllowed(SpecialPermission.S_USER)
public List<EventUser> findAllEventusers(User user) {
user = userFacade.reload(user);
if (!permbean.isCurrentUser(user) && !permbean.getCurrentUser().isSuperadmin()) {
throw new EJBAccessException("Only users themselves can fetch all eventusers for all events");
}
return eventUserFacade.findForUser(user);
}
@Override @Override
@RolesAllowed(EventPermission.S_MANAGE_EVENT) @RolesAllowed(EventPermission.S_MANAGE_EVENT)
......
/*
* Copyright Codecrew Ry
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*/
package fi.codecrew.moya.beans;
import fi.codecrew.moya.facade.EventUserpropertyFacade;
import fi.codecrew.moya.facade.UserEventUserpropertyFacade;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.EventUserproperty;
import fi.codecrew.moya.model.UsersEventUserproperty;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import java.util.List;
@Stateless
@LocalBean
public class UserPropertyBean implements UserPropertyBeanLocal {
@EJB
private EventUserpropertyFacade eventPropertyFacade;
@EJB
private UserEventUserpropertyFacade userPropertyFacade;
@EJB
private PermissionBean permbean;
public UserPropertyBean() {
}
@Override
public List<EventUserproperty> getPropertiesForUser(EventUser user) {
return eventPropertyFacade.findForUser(user);
}
@Override
public List<UsersEventUserproperty> getUserPropertiesForUser(EventUser user) {
return userPropertyFacade.findForUser(user);
}
@Override
public UsersEventUserproperty saveUserproperty(UsersEventUserproperty prop) {
if (prop == null) {
return null;
}
if (prop.getId() == null) {
userPropertyFacade.create(prop);
} else {
prop = userPropertyFacade.merge(prop);
}
return prop;
}
}
...@@ -48,47 +48,50 @@ public class BasicAuthPBean extends ApiAuth implements AuthenticationFormat { ...@@ -48,47 +48,50 @@ public class BasicAuthPBean extends ApiAuth implements AuthenticationFormat {
AuthenticationResult ret = null; AuthenticationResult ret = null;
//String username = UserLoginUtils.getUsernameFromJaasString(jaasUsername); //String username = UserLoginUtils.getUsernameFromJaasString(jaasUsername);
if (password.startsWith(HEADER_PREFIX)) { if (!password.startsWith(HEADER_PREFIX)) {
ret = new AuthenticationResult(); return null;
ret.setUsertype(UserType.REST.name()); }
try { ret = new AuthenticationResult();
String domain = UserLoginUtils.getDomainFromJaasString(username); ret.setUsertype(UserType.REST.name());
LanEvent event = eventbean.getEventForHostname(domain);
String[] pwdsplit = password.split(" "); try {
if (pwdsplit.length != 2) { String domain = UserLoginUtils.getDomainFromJaasString(username);
logger.warn("Rest auth with Basic failed because pwdsplit != 2: user '{}''", username ); LanEvent event = eventbean.getEventForHostname(domain);
return null;
} String[] pwdsplit = password.split(" ");
// There is a possibility that user has a password that starts with "Basic ". To combat this, if (pwdsplit.length != 2) {
// we chech that the authdata is really a base64 string. If not, we continue trying with other methods logger.warn("Rest auth with Basic failed because pwdsplit != 2: user '{}''", username);
String authStr = null; return null;
try { }
authStr = new String(Base64.getDecoder().decode(pwdsplit[1]), UTF8); // There is a possibility that user has a password that starts with "Basic ". To combat this,
} catch (IllegalArgumentException ie) { // we check that the authdata is really a base64 string. If not, we continue trying with other methods
return null; String authStr = null;
} try {
String[] splitStr = authStr.split(PASSWORD_DELIMITER); authStr = new String(Base64.getDecoder().decode(pwdsplit[1]), UTF8);
if (splitStr.length != 4 || !PASSWORD_PREFIX.equals(splitStr[0])) { } catch (IllegalArgumentException ie) {
logger.warn( return null;
"Invalid Basic authentication string '{}'. Authstring must start with {}, followed by appid and app pass", }
authStr, PASSWORD_PREFIX); String[] splitStr = authStr.split(PASSWORD_DELIMITER);
return null; if (splitStr.length != 4 || !PASSWORD_PREFIX.equals(splitStr[0])) {
} logger.warn(
final String appId = splitStr[1]; "Invalid Basic authentication string '{}'. Authstring must start with {}, followed by appid and app pass",
final String userId = splitStr[2]; authStr, PASSWORD_PREFIX);
final String appKey = splitStr[3]; return null;
}
final String appId = splitStr[1];
final String userId = splitStr[2];
final String appKey = splitStr[3];
ApiApplicationInstance appInstance = verifyAppInstance(appId, userId, event); ApiApplicationInstance appInstance = verifyAppInstance(appId, userId, event);
if (appInstance != null && appKey != null && !appKey.isEmpty() && appKey.equals(appInstance.getSecretKey())) { if (appInstance != null && appKey != null && !appKey.isEmpty() && appKey.equals(appInstance.getSecretKey())) {
ret.setUsername(username); ret.setUsername(username);
}
} catch (Exception e) {
ret = null;
logger.warn("Invalid base64 string on Rest Basic auth: " + password, e);
} }
} catch (Exception e) {
ret = null;
logger.warn("Invalid base64 string on Rest Basic auth: " + password, e);
} }
return ret; return ret;
} }
......
...@@ -56,12 +56,14 @@ public class AccountEventFacade extends IntegerPkGenericFacade<AccountEvent> { ...@@ -56,12 +56,14 @@ public class AccountEventFacade extends IntegerPkGenericFacade<AccountEvent> {
CriteriaQuery<Role> cq = cb.createQuery(Role.class); CriteriaQuery<Role> cq = cb.createQuery(Role.class);
Root<AccountEvent> root = cq.from(AccountEvent.class); Root<AccountEvent> root = cq.from(AccountEvent.class);
Path<Role> role = root.get(AccountEvent_.product).get(Product_.provides); Path<Product> prodPath = root.get(AccountEvent_.product);
Path<Role> role = prodPath.get(Product_.provides);
cq.select(role); cq.select(role);
cq.where( cq.where(
cb.equal(role.get(Role_.event), event), cb.equal(role.get(Role_.event), event),
cb.equal(root.get(AccountEvent_.user), u) cb.equal(root.get(AccountEvent_.user), u)
,cb.isEmpty(prodPath.get(Product_.places))
); );
// TypedQuery<Role> q = // TypedQuery<Role> q =
......
...@@ -61,7 +61,7 @@ public class ApiApplicationFacade extends IntegerPkGenericFacade<ApiApplication> ...@@ -61,7 +61,7 @@ public class ApiApplicationFacade extends IntegerPkGenericFacade<ApiApplication>
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<ApiApplication> q = cb.createQuery(ApiApplication.class); CriteriaQuery<ApiApplication> q = cb.createQuery(ApiApplication.class);
Root<ApiApplication> root = q.from(ApiApplication.class); Root<ApiApplication> root = q.from(ApiApplication.class);
q.where(cb.equal(root.get(ApiApplication_.developer), curruser)); q.where(cb.equal(root.get(ApiApplication_.developer), curruser.getUser()));
return getEm().createQuery(q).getResultList(); return getEm().createQuery(q).getResultList();
......
...@@ -26,6 +26,8 @@ import javax.persistence.criteria.Root; ...@@ -26,6 +26,8 @@ import javax.persistence.criteria.Root;
import fi.codecrew.moya.model.*; import fi.codecrew.moya.model.*;
import java.util.List;
@Stateless @Stateless
@LocalBean @LocalBean
public class ApiApplicationInstanceFacade extends IntegerPkGenericFacade<ApiApplicationInstance> { public class ApiApplicationInstanceFacade extends IntegerPkGenericFacade<ApiApplicationInstance> {
...@@ -57,4 +59,16 @@ public class ApiApplicationInstanceFacade extends IntegerPkGenericFacade<ApiAppl ...@@ -57,4 +59,16 @@ public class ApiApplicationInstanceFacade extends IntegerPkGenericFacade<ApiAppl
return super.getSingleNullableResult(getEm().createQuery(q)); return super.getSingleNullableResult(getEm().createQuery(q));
} }
public List<ApiApplicationInstance> findForUser(EventUser currentUser, ApiApplication apiApp) {
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), apiApp),
cb.equal(root.get(ApiApplicationInstance_.eventuser), currentUser)
);
return getEm().createQuery(q).getResultList();
}
} }
...@@ -38,7 +38,7 @@ public class CompoEntryFileFacade extends IntegerPkGenericFacade<CompoEntryFile> ...@@ -38,7 +38,7 @@ public class CompoEntryFileFacade extends IntegerPkGenericFacade<CompoEntryFile>
super(CompoEntryFile.class); super(CompoEntryFile.class);
} }
/*
public List<CompoEntryFile> findFor(CompoEntry entry) { public List<CompoEntryFile> findFor(CompoEntry entry) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<CompoEntryFile> cq = cb.createQuery(CompoEntryFile.class); CriteriaQuery<CompoEntryFile> cq = cb.createQuery(CompoEntryFile.class);
...@@ -47,5 +47,6 @@ public class CompoEntryFileFacade extends IntegerPkGenericFacade<CompoEntryFile> ...@@ -47,5 +47,6 @@ public class CompoEntryFileFacade extends IntegerPkGenericFacade<CompoEntryFile>
cq.where(cb.equal(root.get(CompoEntryFile_.entry), entry)); cq.where(cb.equal(root.get(CompoEntryFile_.entry), entry));
return getEm().createQuery(cq).getResultList(); return getEm().createQuery(cq).getResultList();
} }
*/
} }
package fi.codecrew.moya.facade;
import fi.codecrew.moya.model.*;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
@Stateless
@LocalBean
public class CompoEntryFileTypeFacade extends IntegerPkGenericFacade<CompoEntryFileType> {
public CompoEntryFileTypeFacade() {
super(CompoEntryFileType.class);
}
public CompoEntryFileType findForEntryAndType(Integer entryId, Integer typeId) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<CompoEntryFileType> cq = cb.createQuery(CompoEntryFileType.class);
Root<CompoEntryFileType> root = cq.from(CompoEntryFileType.class);
cq.where(
cb.equal(root.get(CompoEntryFileType_.entry).get(CompoEntry_.id), entryId),
cb.equal(root.get(CompoEntryFileType_.type).get(CompoFileType_.id), typeId)
);
return getSingleNullableResult(getEm().createQuery(cq));
}
}
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
package fi.codecrew.moya.facade; package fi.codecrew.moya.facade;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.ejb.LocalBean; import javax.ejb.LocalBean;
import javax.ejb.Stateless; import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
import fi.codecrew.moya.beans.EventBeanLocal; import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.model.Compo; import fi.codecrew.moya.model.Compo;
import fi.codecrew.moya.model.Compo_; import fi.codecrew.moya.model.Compo_;
import fi.codecrew.moya.model.LanEvent;
@Stateless
@LocalBean @Stateless
public class CompoFacade extends IntegerPkGenericFacade<Compo> { @LocalBean
@EJB public class CompoFacade extends IntegerPkGenericFacade<Compo> {
private EventBeanLocal eventbean; @EJB
private EventBeanLocal eventbean;
public CompoFacade() {
super(Compo.class); public CompoFacade() {
} super(Compo.class);
}
public List<Compo> getList(boolean showHidden) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); public List<Compo> getList(boolean showHidden) {
CriteriaQuery<Compo> cq = cb.createQuery(Compo.class); CriteriaBuilder cb = getEm().getCriteriaBuilder();
Root<Compo> root = cq.from(Compo.class); CriteriaQuery<Compo> cq = cb.createQuery(Compo.class);
Root<Compo> root = cq.from(Compo.class);
ArrayList<Predicate> preds = new ArrayList<>();
preds.add(cb.equal(root.get(Compo_.event), eventbean.getCurrentEvent())); ArrayList<Predicate> preds = new ArrayList<>();
if (!showHidden) { preds.add(cb.equal(root.get(Compo_.event), eventbean.getCurrentEvent()));
preds.add(cb.isFalse(root.get(Compo_.hidden))); if (!showHidden) {
} preds.add(cb.isFalse(root.get(Compo_.hidden)));
cq.where(preds.toArray(new Predicate[preds.size()])); }
cq.orderBy(cb.desc(root.get(Compo_.startTime))); cq.where(preds.toArray(new Predicate[preds.size()]));
List<Compo> ret = getEm().createQuery(cq).getResultList(); cq.orderBy(cb.desc(root.get(Compo_.startTime)));
return ret; List<Compo> ret = getEm().createQuery(cq).getResultList();
} return ret;
} }
@Override
public Compo find(Integer id) {
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_.id), id), cb.equal(root.get(Compo_.event), eventbean.getCurrentEvent()));
return super.getSingleNullableResult(getEm().createQuery(cq));
}
}
/*
* Copyright Codecrew Ry
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*/
package fi.codecrew.moya.facade;
import fi.codecrew.moya.model.*;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
@Stateless
@LocalBean
public class CompoFileTypeFacade extends IntegerPkGenericFacade<CompoFileType> {
public CompoFileTypeFacade() {
super(CompoFileType.class);
}
}
...@@ -199,7 +199,7 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> { ...@@ -199,7 +199,7 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
listQ.setFirstResult(query.getPage() * query.getPagesize()); listQ.setFirstResult(query.getPage() * query.getPagesize());
listQ.setMaxResults(query.getPagesize()); listQ.setMaxResults(query.getPagesize());
} }
return new SearchResult<EventUser>(listQ.getResultList(), countQ.getSingleResult()); return new SearchResult<>(listQ.getResultList(), countQ.getSingleResult());
} }
...@@ -211,6 +211,14 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> { ...@@ -211,6 +211,14 @@ public class EventUserFacade extends IntegerPkGenericFacade<EventUser> {
return getSingleNullableResult(getEm().createQuery(cq)); return getSingleNullableResult(getEm().createQuery(cq));
} }
public List<EventUser> findForUser(User user) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<EventUser> cq = cb.createQuery(EventUser.class);
Root<EventUser> root = cq.from(EventUser.class);
cq.where(cb.equal(root.get(EventUser_.user), user));
return getEm().createQuery(cq).getResultList();
}
// private Predicate addAcPredicate(CriteriaBuilder cb, UserSearchQuery // private Predicate addAcPredicate(CriteriaBuilder cb, UserSearchQuery
// query, Root<AccountEvent> root) { // query, Root<AccountEvent> root) {
// Expression<BigDecimal> sum = // Expression<BigDecimal> sum =
......
/*
* Copyright Codecrew Ry
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*/
package fi.codecrew.moya.facade;
import fi.codecrew.moya.beans.UserBean;
import fi.codecrew.moya.model.*;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@Stateless
@LocalBean
public class EventUserpropertyFacade extends IntegerPkGenericFacade<EventUserproperty> {
public EventUserpropertyFacade() {
super(EventUserproperty.class);
}
@EJB
private UserBean userbean;
public List<EventUserproperty> findForUser(EventUser user) {
CriteriaBuilder cq = getEm().getCriteriaBuilder();
CriteriaQuery<EventUserproperty> cb = cq.createQuery(EventUserproperty.class);
Root<EventUserproperty> root = cb.from(EventUserproperty.class);
Set<Role> roles = userbean.localFindUsersRoles(user);
if(roles == null || roles.isEmpty()){
return Collections.emptyList();
}
Path<Role> rolePath = root.get(EventUserproperty_.forRole);
cb.where(
cq.equal(root.get(EventUserproperty_.event), user.getEvent()),
cq.or(cq.isNull(rolePath), rolePath.in(roles))
);
return getEm().createQuery(cb).getResultList();
}
}
/*
* Copyright Codecrew Ry
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*/
package fi.codecrew.moya.facade;
import fi.codecrew.moya.model.*;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import java.util.List;
@Stateless
@LocalBean
public class UserEventUserpropertyFacade extends IntegerPkGenericFacade<UsersEventUserproperty> {
public UserEventUserpropertyFacade() {
super(UsersEventUserproperty.class);
}
public List<UsersEventUserproperty> findForUser(EventUser user) {
CriteriaBuilder cq = getEm().getCriteriaBuilder();
CriteriaQuery<UsersEventUserproperty> cb = cq.createQuery(UsersEventUserproperty.class);
Root<UsersEventUserproperty> root = cb.from(UsersEventUserproperty.class);
cb.where(
cq.equal(root.get(UsersEventUserproperty_.user), user)
);
return getEm().createQuery(cb).getResultList();
}
}
...@@ -18,10 +18,7 @@ ...@@ -18,10 +18,7 @@
*/ */
package fi.codecrew.moya.facade; package fi.codecrew.moya.facade;
import fi.codecrew.moya.model.Allergy; import fi.codecrew.moya.model.*;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.UsersAllergy;
import fi.codecrew.moya.model.UsersAllergy_;
import javax.ejb.LocalBean; import javax.ejb.LocalBean;
import javax.ejb.Stateless; import javax.ejb.Stateless;
...@@ -39,12 +36,12 @@ public class UsersAllergyFacade extends IntegerPkGenericFacade<UsersAllergy> { ...@@ -39,12 +36,12 @@ public class UsersAllergyFacade extends IntegerPkGenericFacade<UsersAllergy> {
} }
public List<UsersAllergy> findForUser(EventUser user) { public List<UsersAllergy> findForUser(User user) {
CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<UsersAllergy> cq = cb.createQuery(UsersAllergy.class); CriteriaQuery<UsersAllergy> cq = cb.createQuery(UsersAllergy.class);
Root<UsersAllergy> root = cq.from(UsersAllergy.class); Root<UsersAllergy> root = cq.from(UsersAllergy.class);
cq.where(cb.equal(root.get(UsersAllergy_.user), user.getUser())); cq.where(cb.equal(root.get(UsersAllergy_.user), user));
return getEm().createQuery(cq).getResultList(); return getEm().createQuery(cq).getResultList();
} }
......
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
package fi.codecrew.moya.facade.callbacks; package fi.codecrew.moya.facade.callbacks;
import java.util.ArrayList; import java.util.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.*;
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 fi.codecrew.moya.model.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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.Role_;
import fi.codecrew.moya.utilities.jpa.FacadeCallback; import fi.codecrew.moya.utilities.jpa.FacadeCallback;
public class EventUserRolefilter implements FacadeCallback<EventUser> { public class EventUserRolefilter implements FacadeCallback<EventUser> {
private final List<Role> roles; private final List<Role> roles;
private static final Logger logger = LoggerFactory.getLogger(EventUserRolefilter.class); private static final Logger logger = LoggerFactory.getLogger(EventUserRolefilter.class);
private final LanEvent event;
public EventUserRolefilter(List<Role> filters) { public EventUserRolefilter(List<Role> filters) {
roles = filters; roles = Collections.unmodifiableList(filters);
event = roles.get(0).getEvent();
} }
private static final Set<Integer> getAllChildren(Collection<Role> roles, Set<Integer> checkedRoles) { private static final Set<Integer> getAllChildren(Collection<Role> roles, Set<Integer> checkedRoles) {
if (checkedRoles == null) {
for (Role role : roles) checkedRoles = new HashSet<>();
{ }
for (Role role : roles) {
if (role == null || checkedRoles.contains(role.getId())) { if (role == null || checkedRoles.contains(role.getId())) {
continue; continue;
} }
...@@ -66,40 +53,112 @@ public class EventUserRolefilter implements FacadeCallback<EventUser> { ...@@ -66,40 +53,112 @@ public class EventUserRolefilter implements FacadeCallback<EventUser> {
return checkedRoles; return checkedRoles;
} }
private static final Set<Integer> getAllParents(Collection<Role> roles, Set<Integer> checkedRoles) {
if (checkedRoles == null) {
checkedRoles = new HashSet<>();
}
for (Role role : roles) {
if (role == null || checkedRoles.contains(role.getId())) {
continue;
}
checkedRoles.add(role.getId());
getAllParents(role.getParents(), checkedRoles);
}
return checkedRoles;
}
public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates, boolean isFullQuery) { public void exec(CriteriaBuilder cb, CriteriaQuery<?> cq, Path<EventUser> root, List<Predicate> predicates, boolean isFullQuery) {
if (roles != null && !roles.isEmpty()) if (roles == null || roles.isEmpty()) {
return;
}
Set<Integer> roleWChildrenIds = getAllChildren(roles, null);
Set<Integer> roleWParentsIds = getAllParents(roles, null);
logger.warn("roles with children: {}, roles with parent {}", roleWChildrenIds, roleWParentsIds);
Path<Integer> rootId = root.get(EventUser_.id);
ArrayList<Predicate> orPreds = new ArrayList<Predicate>();
/**
* Find all users that have a role "forced" directly to the user
* If role has parents, user belongs also to them, so also parents are included
*/
{ {
HashSet<Integer> roleids = new HashSet<Integer>(); Subquery<Integer> subq = cq.subquery(Integer.class);
getAllChildren(roles, roleids); Root<Role> subroot = subq.from(Role.class);
logger.debug("Requiring roles {}", roleids); subq.select(subroot.join(Role_.users).get(EventUser_.id));
Path<Integer> rootId = root.get(EventUser_.id);
ArrayList<Predicate> orPreds = new ArrayList<Predicate>();
{
Subquery<Integer> subq = cq.subquery(Integer.class);
Root<Role> subroot = subq.from(Role.class);
subq.select(subroot.join(Role_.users).get(EventUser_.id));
subq.where(subroot.get(Role_.id).in(roleids));
orPreds.add(rootId.in(subq));
}
{ // Root<Role> rolePath = subq.correlate(roleRoot);
Subquery<Integer> subq = cq.subquery(Integer.class);
Root<Role> subroot = subq.from(Role.class);
subq.select(subroot.join(Role_.productsProvide).join(Product_.accountEvents).get(AccountEvent_.user).get(EventUser_.id));
subq.where(subroot.get(Role_.id).in(roleids));
orPreds.add(rootId.in(subq));
}
{
Subquery<Integer> subq = cq.subquery(Integer.class);
Root<Role> subroot = subq.from(Role.class);
subq.select(subroot.join(Role_.productsProvide).join(Product_.places).get(Place_.placeReserver).get(GroupMembership_.user).get(EventUser_.id));
subq.where(subroot.get(Role_.id).in(roleids));
orPreds.add(rootId.in(subq));
}
predicates.add(cb.or(orPreds.toArray(new Predicate[orPreds.size()]))); subq.where(subroot.get(Role_.id).in(roleWChildrenIds));
orPreds.add(rootId.in(subq));
}
/**
* Find all products that provide a given role, or a parent of the role via accountevents
* NOTE! Products that have places, do not provide roles to users
*/
{
Subquery<Integer> subq = cq.subquery(Integer.class);
Root<Role> subroot = subq.from(Role.class);
ListJoin<Role, Product> prodsPath = subroot.join(Role_.productsProvide);
subq.select(prodsPath.join(Product_.accountEvents).get(AccountEvent_.user).get(EventUser_.id));
subq.where(
subroot.get(Role_.id).in(roleWChildrenIds),
cb.isEmpty(prodsPath.get(Product_.places))
);
orPreds.add(rootId.in(subq));
} }
/**
* Roles provided by products via places user has been given to.
*/
{
Subquery<Integer> subq = cq.subquery(Integer.class);
Root<Role> subroot = subq.from(Role.class);
subq.select(subroot.join(Role_.productsProvide).join(Product_.places).get(Place_.placeReserver).get(GroupMembership_.user).get(EventUser_.id));
subq.where(subroot.get(Role_.id).in(roleWChildrenIds));
orPreds.add(rootId.in(subq));
}
/** Roles provided by places user has been given to.
*/
{
Subquery<Integer> subq = cq.subquery(Integer.class);
Root<Role> subroot = subq.from(Role.class);
subq.select(subroot.join(Role_.placesProvide).get(Place_.placeReserver).get(GroupMembership_.user).get(EventUser_.id));
subq.where(subroot.get(Role_.id).in(roleWChildrenIds));
orPreds.add(rootId.in(subq));
}
/** Find all roles provided by organisation roles
*
*/
{
Subquery<Integer> subq = cq.subquery(Integer.class);
Root<Role> subroot = subq.from(Role.class);
subroot.get(Role_.orgRoles);
ListJoin<OrgRole, User> orgRoleUser = subroot.join(Role_.orgRoles).join(OrgRole_.users);
ListJoin<User, EventUser> euJoin = orgRoleUser.join(User_.eventusers);
subq.select(euJoin.get(EventUser_.id));
subq.where(
cb.equal(euJoin.get(EventUser_.event), event),
subroot.get(Role_.id).in(roleWChildrenIds));
orPreds.add(rootId.in(subq));
}
predicates.add(cb.or(orPreds.toArray(new Predicate[orPreds.size()])));
} }
} }
...@@ -142,12 +142,12 @@ public class ApiApplication extends GenericEntity { ...@@ -142,12 +142,12 @@ public class ApiApplication extends GenericEntity {
this.readerType = readerType; this.readerType = readerType;
} }
public List<ApiApplicationInstance> getInstances() { private List<ApiApplicationInstance> getInstances() {
return instances; throw new RuntimeException("DO NOT USE. Only for metamodel generation");
} }
public void setInstances(List<ApiApplicationInstance> instances) { public void setInstances(List<ApiApplicationInstance> instances) {
this.instances = instances; throw new RuntimeException("DO NOT USE. Only for metamodel generation");
} }
} }
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
/* /*
* To change this template, choose Tools | Templates * To change this template, choose Tools | Templates
...@@ -72,7 +72,7 @@ public class Compo extends GenericEntity { ...@@ -72,7 +72,7 @@ public class Compo extends GenericEntity {
/** /**
* When the voting should start * When the voting should start
* *
* @see {@link #holdVoting} * @see {@link #holdVoting}
*/ */
@Column(name = "vote_start") @Column(name = "vote_start")
...@@ -109,14 +109,6 @@ public class Compo extends GenericEntity { ...@@ -109,14 +109,6 @@ public class Compo extends GenericEntity {
@Column(name = "hidden", nullable = false) @Column(name = "hidden", nullable = false)
private boolean hidden = false; private boolean hidden = false;
public boolean isHidden() {
return hidden;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
/** /**
* Entries submitted to participate this compo. * Entries submitted to participate this compo.
*/ */
...@@ -124,6 +116,19 @@ public class Compo extends GenericEntity { ...@@ -124,6 +116,19 @@ public class Compo extends GenericEntity {
@OrderBy("sort") @OrderBy("sort")
private List<CompoEntry> compoEntries; private List<CompoEntry> compoEntries;
@OneToMany(mappedBy = "compo")
@OrderBy("sort")
private List<CompoFileType> filetypes;
@ManyToOne()
@JoinColumn(name = "entrysubmit_role_id",referencedColumnName = "id")
private Role entrysubmitRole;
@ManyToOne()
@JoinColumn(name = "voting_scheme_id", referencedColumnName = "id")
private CompoVotingScheme votingScheme;
public Compo(String compoName, boolean holdVoting) { public Compo(String compoName, boolean holdVoting) {
this(); this();
...@@ -131,18 +136,24 @@ public class Compo extends GenericEntity { ...@@ -131,18 +136,24 @@ public class Compo extends GenericEntity {
this.holdVoting = holdVoting; this.holdVoting = holdVoting;
} }
public boolean isSubmit() public boolean isHidden() {
{ return hidden;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public boolean isSubmit() {
Date now = new Date(); Date now = new Date();
return now.after(getSubmitStart()) && now.before(getSubmitEnd()); return now.after(getSubmitStart()) && now.before(getSubmitEnd());
} }
public boolean isVote() public boolean isVote() {
{
Date now = new Date(); Date now = new Date();
return !getHoldVoting() && return !getHoldVoting() &&
now.after(getVoteStart()) && now.after(getVoteStart()) &&
now.before(getVoteEnd()); now.before(getVoteEnd());
} }
public Compo() { public Compo() {
...@@ -229,8 +240,7 @@ public class Compo extends GenericEntity { ...@@ -229,8 +240,7 @@ public class Compo extends GenericEntity {
} }
/** /**
* @param maxParticipantCount * @param maxParticipantCount the maxParticipantCount to set
* the maxParticipantCount to set
*/ */
public void setMaxParticipantCount(int maxParticipantCount) { public void setMaxParticipantCount(int maxParticipantCount) {
this.maxParticipantCount = maxParticipantCount; this.maxParticipantCount = maxParticipantCount;
...@@ -252,4 +262,31 @@ public class Compo extends GenericEntity { ...@@ -252,4 +262,31 @@ public class Compo extends GenericEntity {
this.endTime = endTime; this.endTime = endTime;
} }
public boolean isHoldVoting() {
return holdVoting;
}
public List<CompoFileType> getFiletypes() {
return filetypes;
}
public void setFiletypes(List<CompoFileType> filetypes) {
this.filetypes = filetypes;
}
public Role getEntrysubmitRole() {
return entrysubmitRole;
}
public void setEntrysubmitRole(Role entrysubmitRole) {
this.entrysubmitRole = entrysubmitRole;
}
public CompoVotingScheme getVotingScheme() {
return votingScheme;
}
public void setVotingScheme(CompoVotingScheme votingScheme) {
this.votingScheme = votingScheme;
}
} }
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
/* /*
* To change this template, choose Tools | Templates * To change this template, choose Tools | Templates
...@@ -23,6 +23,7 @@ ...@@ -23,6 +23,7 @@
package fi.codecrew.moya.model; package fi.codecrew.moya.model;
import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
...@@ -39,7 +40,7 @@ import javax.persistence.Temporal; ...@@ -39,7 +40,7 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
/** /**
* *
*/ */
@Entity @Entity
@Table(name = "compo_entries") @Table(name = "compo_entries")
...@@ -74,9 +75,8 @@ public class CompoEntry extends GenericEntity { ...@@ -74,9 +75,8 @@ public class CompoEntry extends GenericEntity {
@Column(name = "final_position") @Column(name = "final_position")
private Integer finalPosition; private Integer finalPosition;
@JoinColumn(name = "current_file_id", referencedColumnName = CompoEntryFile.ID_COLUMN) @OneToMany(mappedBy = "entry")
@OneToOne private List<CompoEntryFileType> filetypes = new ArrayList<>();
private CompoEntryFile currentFile;
@OneToMany(mappedBy = "compoEntry") @OneToMany(mappedBy = "compoEntry")
private List<Vote> votes; private List<Vote> votes;
...@@ -93,8 +93,7 @@ public class CompoEntry extends GenericEntity { ...@@ -93,8 +93,7 @@ public class CompoEntry extends GenericEntity {
@ManyToOne @ManyToOne
private EventUser creator; private EventUser creator;
public Integer getVotetotal() public Integer getVotetotal() {
{
int votetotal = 0; int votetotal = 0;
for (Vote v : getVotes()) { for (Vote v : getVotes()) {
votetotal += v.getScore(); votetotal += v.getScore();
...@@ -151,7 +150,7 @@ public class CompoEntry extends GenericEntity { ...@@ -151,7 +150,7 @@ public class CompoEntry extends GenericEntity {
} }
public void setParticipants( public void setParticipants(
List<CompoEntryParticipant> compoEntryParticipantList) { List<CompoEntryParticipant> compoEntryParticipantList) {
this.participants = compoEntryParticipantList; this.participants = compoEntryParticipantList;
} }
...@@ -195,4 +194,11 @@ public class CompoEntry extends GenericEntity { ...@@ -195,4 +194,11 @@ public class CompoEntry extends GenericEntity {
this.author = author; this.author = author;
} }
public List<CompoEntryFileType> getFiletypes() {
return filetypes;
}
public void setFiletypes(List<CompoEntryFileType> filetypes) {
this.filetypes = filetypes;
}
} }
...@@ -26,6 +26,7 @@ package fi.codecrew.moya.model; ...@@ -26,6 +26,7 @@ package fi.codecrew.moya.model;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import javax.persistence.Basic; import javax.persistence.Basic;
import javax.persistence.Column; import javax.persistence.Column;
...@@ -49,6 +50,9 @@ import org.slf4j.LoggerFactory; ...@@ -49,6 +50,9 @@ import org.slf4j.LoggerFactory;
@Table(name = "compo_entry_files") @Table(name = "compo_entry_files")
public class CompoEntryFile extends GenericEntity { public class CompoEntryFile extends GenericEntity {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(CompoEntryFile.class);
@Column(name = "mime_type") @Column(name = "mime_type")
private String mimeType; private String mimeType;
...@@ -62,28 +66,21 @@ public class CompoEntryFile extends GenericEntity { ...@@ -62,28 +66,21 @@ public class CompoEntryFile extends GenericEntity {
@Column(name = "hash", updatable = false) @Column(name = "hash", updatable = false)
private String hash; private String hash;
@Lob @Column(name="filepath", updatable = false, nullable = false)
@Column(name = "file_data", updatable = false) private String filepath;
@Basic(fetch = FetchType.LAZY)
private byte[] fileData;
@Column(name = "uploaded", nullable = false) @Column(name = "uploaded", nullable = false)
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Calendar uploaded = Calendar.getInstance(); private Date uploaded = new Date();
@ManyToOne(optional=false)
@JoinColumn(name="entryfiletype_id", referencedColumnName = "id", nullable = false, updatable = false)
private CompoEntryFileType filetype;
@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() { public CompoEntryFile() {
super(); super();
} }
public CompoEntryFile(CompoEntry entry) {
this.entry = entry;
}
public String getMimeType() { public String getMimeType() {
return mimeType; return mimeType;
} }
...@@ -116,42 +113,28 @@ public class CompoEntryFile extends GenericEntity { ...@@ -116,42 +113,28 @@ public class CompoEntryFile extends GenericEntity {
this.hash = hash; this.hash = hash;
} }
public byte[] getFileData() { public Date getUploaded() {
return fileData;
}
public void setFileData(byte[] fileData) {
this.fileData = fileData;
this.hash = getShaChecksum(fileData);
}
public Calendar getUploaded() {
return uploaded; return uploaded;
} }
public void setUploaded(Calendar uploaded) { public void setUploaded(Date uploaded) {
this.uploaded = uploaded; this.uploaded = uploaded;
} }
public CompoEntry getEntriesId() {
return entry; public CompoEntryFileType getFiletype() {
return filetype;
} }
public void setEntriesId(CompoEntry entriesId) { public void setFiletype(CompoEntryFileType filetype) {
this.entry = entriesId; this.filetype = filetype;
} }
public static String getShaChecksum(byte[] data) public String getFilepath() {
{ return filepath;
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;
} }
public void setFilepath(String filepath) {
this.filepath = filepath;
}
} }
package fi.codecrew.moya.model;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
import static fi.codecrew.moya.model.CompoEntryFileType.ENTRY_ID_COLUMN;
import static fi.codecrew.moya.model.CompoEntryFileType.TYPE_ID_COLUMN;
@Entity
@Table(name = "compo_entry_file_types", uniqueConstraints = @UniqueConstraint(columnNames = {ENTRY_ID_COLUMN, TYPE_ID_COLUMN}))
public class CompoEntryFileType extends GenericEntity {
public static final String ENTRY_ID_COLUMN = "entry_id";
public static final String TYPE_ID_COLUMN = "type_id";
@ManyToOne(optional = false)
@JoinColumn(name = ENTRY_ID_COLUMN, nullable = false, updatable = false)
private CompoEntry entry;
@ManyToOne(optional = false)
@JoinColumn(name = TYPE_ID_COLUMN, nullable = false, updatable = false)
private CompoFileType type;
@ManyToOne(optional = false)
@JoinColumn(name = "current_file_id")
private CompoEntryFile currentFile;
@OneToMany(mappedBy = "filetype")
// This is here only for metamodel generation.
private List<CompoEntryFile> entryFiles;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="updated", nullable = false)
private Date updated = new Date();
public CompoEntry getEntry() {
return entry;
}
public void setEntry(CompoEntry entry) {
this.entry = entry;
}
public CompoFileType getType() {
return type;
}
public void setType(CompoFileType type) {
this.type = type;
}
public CompoEntryFile getCurrentFile() {
return currentFile;
}
public void setCurrentFile(CompoEntryFile currentFile) {
this.currentFile = currentFile;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public List<CompoEntryFile> getEntryFiles() {
return entryFiles;
}
public void setEntryFiles(List<CompoEntryFile> entryFiles) {
this.entryFiles = entryFiles;
}
}
package fi.codecrew.moya.model;
import javax.persistence.*;
import java.util.List;
@Table(name = "compo_file_types")
@Entity
public class CompoFileType extends GenericEntity {
public enum FileType {
DATA, THUMBNAIL, MUSIC_PREVIEW
}
@ManyToOne(optional = false)
@JoinColumn(name = "compo_id", nullable = false, updatable = false)
private Compo compo;
/*
@OneToMany(mappedBy = "filetype")
// Only here for metamodel.. Do not create getter and setter!
private List<CompoEntryFile> entryfiles;
*/
@Lob
@Column(name = "name")
private String name;
@Lob
@Column(name = "description")
private String description;
@Column(nullable = false)
private int sort = 100;
@Column(name = "required")
private boolean required = false;
@Enumerated(EnumType.STRING)
@Column(name = "filetype")
private FileType filetype = FileType.DATA;
public Compo getCompo() {
return compo;
}
public void setCompo(Compo compo) {
this.compo = compo;
}
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 boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public FileType getFiletype() {
return filetype;
}
public void setFiletype(FileType filetype) {
this.filetype = filetype;
}
}
package fi.codecrew.moya.model;
import javax.persistence.*;
import java.math.BigDecimal;
import static fi.codecrew.moya.model.CompoVotingRole.SCHEME_ID_COLUMN;
import static fi.codecrew.moya.model.CompoVotingRole.ROLE_ID_COLUMN;
@Table(name = "compo_voting_roles", uniqueConstraints = @UniqueConstraint(columnNames = {SCHEME_ID_COLUMN, ROLE_ID_COLUMN}))
@Entity
public class CompoVotingRole extends GenericEntity {
static final String SCHEME_ID_COLUMN = "scheme_id";
static final String ROLE_ID_COLUMN = "role_id";
@ManyToOne()
@JoinColumn(nullable = false, updatable = false, name = SCHEME_ID_COLUMN)
private CompoVotingScheme scheme;
@Column(nullable = false)
private int priority = 100;
@ManyToOne
@JoinColumn(nullable = false, updatable = false, name = ROLE_ID_COLUMN)
private Role role;
@Column(nullable = false, precision = 24, scale = 8, name = "multiplier")
private BigDecimal multiplier = BigDecimal.ONE;
@Column(name = "override_min", scale = 24, precision = 8)
private BigDecimal overrideMin;
@Column(name = "override_max", scale = 24, precision = 8)
private BigDecimal overrideMax;
@Column(nullable = false, name = "override_others")
private boolean overrideOthers = false;
public CompoVotingScheme getScheme() {
return scheme;
}
public void setScheme(CompoVotingScheme scheme) {
this.scheme = scheme;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public BigDecimal getMultiplier() {
return multiplier;
}
public void setMultiplier(BigDecimal multiplier) {
this.multiplier = multiplier;
}
public BigDecimal getOverrideMin() {
return overrideMin;
}
public void setOverrideMin(BigDecimal overrideMin) {
this.overrideMin = overrideMin;
}
public BigDecimal getOverrideMax() {
return overrideMax;
}
public void setOverrideMax(BigDecimal overrideMax) {
this.overrideMax = overrideMax;
}
public boolean isOverrideOthers() {
return overrideOthers;
}
public void setOverrideOthers(boolean overrideOthers) {
this.overrideOthers = overrideOthers;
}
}
package fi.codecrew.moya.model;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
@Table(name = "compo_voting_schemes")
@Entity
public class CompoVotingScheme extends GenericEntity {
public enum SchemeType {
INT_TO_ALL_ENTRIES,
SORT_BEST_N,
}
@ManyToOne(optional = false)
@JoinColumn(nullable = false, updatable = false, name = "event_id")
private LanEvent event;
@Enumerated(EnumType.STRING)
@Column(nullable = false, name = "type")
private SchemeType type = SchemeType.INT_TO_ALL_ENTRIES;
@Column(nullable = false, name = "name")
private String name;
@OneToMany(mappedBy = "scheme")
@OrderBy("priority")
private List<CompoVotingRole> votingRoles;
@Column(name = "min_value", scale = 24, precision = 8)
private BigDecimal minValue = BigDecimal.ONE;
@Column(name = "max_value", scale = 24, precision = 8)
private BigDecimal maxValue = BigDecimal.TEN;
@Column(name = "value_increment", scale = 24, precision = 8)
private BigDecimal valueIncrement = BigDecimal.ONE;
@Column(name = "allow_recusal", nullable = false)
private boolean allowRecusal = false;
public LanEvent getEvent() {
return event;
}
public void setEvent(LanEvent event) {
this.event = event;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<CompoVotingRole> getVotingRoles() {
return votingRoles;
}
public void setVotingRoles(List<CompoVotingRole> votingRoles) {
this.votingRoles = votingRoles;
}
public BigDecimal getMinValue() {
return minValue;
}
public void setMinValue(BigDecimal minValue) {
this.minValue = minValue;
}
public BigDecimal getMaxValue() {
return maxValue;
}
public void setMaxValue(BigDecimal maxValue) {
this.maxValue = maxValue;
}
public BigDecimal getValueIncrement() {
return valueIncrement;
}
public void setValueIncrement(BigDecimal valueIncrement) {
this.valueIncrement = valueIncrement;
}
public boolean isAllowRecusal() {
return allowRecusal;
}
public void setAllowRecusal(boolean allowRecusal) {
this.allowRecusal = allowRecusal;
}
public SchemeType getType() {
return type;
}
public void setType(SchemeType type) {
this.type = type;
}
}
/*
* Copyright Codecrew Ry
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*/
package fi.codecrew.moya.model;
import javax.persistence.*;
@Entity
@Table(name = "event_userproperties")
public class EventUserproperty extends GenericEntity {
public enum PropertyType {
STRING, INTEGER, DECIMAL, IMAGE, BLOB
}
@ManyToOne(optional = false)
@JoinColumn(nullable = false, updatable = false, name = "event_id", referencedColumnName = "id")
private LanEvent event;
@Convert(converter = LanguageAwareStringConverter.class )
@Column(nullable = false, columnDefinition = "jsonb not null", name="name")
private LanguageAwareString name;
@Convert(converter = LanguageAwareStringConverter.class )
@Column(nullable = false, columnDefinition = "jsonb not null", name="description")
private LanguageAwareString description;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private PropertyType type = PropertyType.STRING;
@ManyToOne
@JoinColumn(nullable = true, name = "for_role_id", referencedColumnName = "id")
private Role forRole;
public LanEvent getEvent() {
return event;
}
public void setEvent(LanEvent event) {
this.event = event;
}
public PropertyType getType() {
return type;
}
public void setType(PropertyType type) {
this.type = type;
}
public LanguageAwareString getName() {
return name;
}
public void setName(LanguageAwareString name) {
this.name = name;
}
public LanguageAwareString getDescription() {
return description;
}
public void setDescription(LanguageAwareString description) {
this.description = description;
}
public Role getForRole() {
return forRole;
}
public void setForRole(Role forRole) {
this.forRole = forRole;
}
}
...@@ -39,10 +39,10 @@ public class GenericEntity extends EntityEquals implements ModelInterface, Entit ...@@ -39,10 +39,10 @@ public class GenericEntity extends EntityEquals implements ModelInterface, Entit
private static final long serialVersionUID = -9041737052951021560L; private static final long serialVersionUID = -9041737052951021560L;
@Id @Id
@Column(name = ID_COLUMN, nullable = false, updatable = false) @Column(name = ID_COLUMN, nullable = false, updatable = false, columnDefinition = "SERIAL NOT NULL")
private Integer id; private Integer id;
@Column(name = "meta", columnDefinition = "json") @Column(name = "meta", columnDefinition = "jsonb")
private JsonObject meta; private JsonObject meta;
@Override @Override
......
...@@ -25,6 +25,9 @@ public class LanguageAwareString { ...@@ -25,6 +25,9 @@ public class LanguageAwareString {
} }
return ret; return ret;
} }
public String getDefaultValue(){
return getValue(defaultLanguage);
}
public String getDefaultLanguage() { public String getDefaultLanguage() {
return defaultLanguage; return defaultLanguage;
......
...@@ -138,6 +138,18 @@ public class User extends GenericEntity implements IUser { ...@@ -138,6 +138,18 @@ public class User extends GenericEntity implements IUser {
@OrderBy() @OrderBy()
private List<LicenseCode> licenseCodes; private List<LicenseCode> licenseCodes;
@OneToMany(mappedBy="user", fetch = FetchType.LAZY)
private List<EventUser> eventusers;
private List<EventUser> getEventusers(){
throw new RuntimeException("We never want to fetch this. Only here for metamodel");
}
private void setEventusers(List<EventUser> eventusers){
throw new RuntimeException("We never want to fetch this. Only here for metamodel");
}
@Transient @Transient
private static final Logger logger = LoggerFactory.getLogger(User.class); private static final Logger logger = LoggerFactory.getLogger(User.class);
......
...@@ -3,34 +3,35 @@ package fi.codecrew.moya.model; ...@@ -3,34 +3,35 @@ package fi.codecrew.moya.model;
import javax.persistence.*; import javax.persistence.*;
import java.util.Date; import java.util.Date;
@Table(name="user_allergies") @Table(name = "user_allergies")
@Entity @Entity
public class UsersAllergy extends GenericEntity { public class UsersAllergy extends GenericEntity {
@Column(nullable=false, name = "selected") @Column(nullable = false, name = "selected")
private boolean selected = false; private boolean selected = false;
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
@Column(name="severity") @Column(name = "severity")
private AllergySeverity severity = AllergySeverity.NORMAL; private AllergySeverity severity = AllergySeverity.NORMAL;
@ManyToOne @ManyToOne
@JoinColumn(name="user_id", updatable = false, referencedColumnName = "id", nullable = false) @JoinColumn(name = "user_id", updatable = false, referencedColumnName = "id", nullable = false)
private User user; private User user;
@ManyToOne @ManyToOne
@JoinColumn(name="allergy_id", updatable = false, referencedColumnName = "id", nullable = false) @JoinColumn(name = "allergy_id", updatable = false, referencedColumnName = "id", nullable = false)
private Allergy allergy; private Allergy allergy;
@Column(name="created") @Column(name = "created")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date created; private Date created;
@Lob @Lob
@Column(name="notes") @Column(name = "notes")
private String notes; private String notes;
public UsersAllergy() { public UsersAllergy() {
super(); super();
} }
...@@ -80,4 +81,12 @@ public class UsersAllergy extends GenericEntity { ...@@ -80,4 +81,12 @@ public class UsersAllergy extends GenericEntity {
public void setSelected(boolean selected) { public void setSelected(boolean selected) {
this.selected = selected; this.selected = selected;
} }
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
} }
/*
* Copyright Codecrew Ry
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*/
package fi.codecrew.moya.model;
import javax.persistence.*;
import java.math.BigDecimal;
import java.math.BigInteger;
@Entity
@Table(name = "users_event_userproperties")
public class UsersEventUserproperty extends GenericEntity {
@ManyToOne(optional = false)
@JoinColumn(name = "property_id", updatable = false, nullable = false)
private EventUserproperty property;
@ManyToOne(optional = false)
@JoinColumn(name = "user_id", updatable = false, nullable = false)
private EventUser user;
@Lob
@Column(name = "textvalue")
private String textvalue = "";
@Column(name = "integervalue")
private BigInteger integerValue;
@Column(name = "decimalvalue", scale = 38, precision = 10)
private BigDecimal decimalValue;
@Lob
@Column(name = "datavalue")
private byte[] dataValue;
public UsersEventUserproperty() {
super();
}
public UsersEventUserproperty(EventUserproperty prop, EventUser eventuser) {
super();
this.property = prop;
this.user = eventuser;
}
public EventUserproperty getProperty() {
return property;
}
public void setProperty(EventUserproperty property) {
this.property = property;
}
public EventUser getUser() {
return user;
}
public void setUser(EventUser user) {
this.user = user;
}
public String getTextvalue() {
return textvalue;
}
public void setTextvalue(String textvalue) {
this.textvalue = textvalue;
}
public BigInteger getIntegerValue() {
return integerValue;
}
public void setIntegerValue(BigInteger integerValue) {
this.integerValue = integerValue;
}
public BigDecimal getDecimalValue() {
return decimalValue;
}
public void setDecimalValue(BigDecimal decimalValue) {
this.decimalValue = decimalValue;
}
public byte[] getDataValue() {
return dataValue;
}
public void setDataValue(byte[] dataValue) {
this.dataValue = dataValue;
}
}
...@@ -14,7 +14,9 @@ ...@@ -14,7 +14,9 @@
<property name="eclipselink.target-server" value="Glassfish" /> <property name="eclipselink.target-server" value="Glassfish" />
<property name="eclipselink.session.customizer" <property name="eclipselink.session.customizer"
value="fi.codecrew.moya.database.eclipselink.MoyaSessionCustomizer" /> value="fi.codecrew.moya.database.eclipselink.MoyaSessionCustomizer" />
<property name="eclipselink.ddl-generation" value="none"/> <property name="eclipselink.ddl-generation" value="create-tables"/>
<!--property name="eclipselink.ddl-generation" value="create-tables"/-->
<property name="eclipselink.ddl-generation.output-mode" value="sql-script"/> <property name="eclipselink.ddl-generation.output-mode" value="sql-script"/>
</properties> </properties>
......
...@@ -170,6 +170,11 @@ ...@@ -170,6 +170,11 @@
<version>${findbugs.version}</version> <version>${findbugs.version}</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>9.0</version>
</dependency>
</dependencies> </dependencies>
<reporting> <reporting>
<plugins> <plugins>
......
...@@ -15,6 +15,7 @@ public enum SystemProperty { ...@@ -15,6 +15,7 @@ public enum SystemProperty {
MOYA_IRC_SERVER, MOYA_IRC_SERVER,
MOYA_IRC_CHANNEL("#moya-debug"), MOYA_IRC_CHANNEL("#moya-debug"),
MOYA_IRC_SERVERPASS(), MOYA_IRC_SERVERPASS(),
MOYA_COMPOFILE_DIR("/tmp/moya"),
; ;
......
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<h:body>
<ui:composition template="#{sessionHandler.template}">
<f:metadata>
<f:event type="preRenderView"
listener="#{applicationApiView.initSuperApplicationListView}" />
</f:metadata>
<ui:define name="content">
<button></button>
<div style="display:none;" id="createApp">
</div>
<h1>#{i18n['apiapp.edit.applist']}</h1>
<p:dataTable value="#{applicationApiView.applist}" var="app">
<p:column headerText="#{i18n['apiapp.name']}">
<h:outputText value="#{app.name}" />
</p:column>
<p:column headerText="#{i18n['apiapp.description']}">
<h:outputText value="#{app.description}" />
</p:column>
<p:column>
<h:outputText value="#{app.created}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}"
timeZone="#{sessionHandler.timezone}" />
</h:outputText>
</p:column>
<p:column headerText="#{i18n['apiapp.enabled']}">
<h:outputText value="#{app.enabled}" />
</p:column>
</p:dataTable>
</ui:define>
</ui:composition>
</h:body>
</html>
\ No newline at end of file
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<h:body>
<ui:composition template="#{sessionHandler.template}">
<f:metadata>
<f:viewParam name="id" value="#{apiAppEditView.id}"/>
<f:event type="preRenderView"
listener="#{apiAppEditView.initEdit}"/>
</f:metadata>
<ui:define name="content">
<h1>#{i18n['apiapp.edit.applist']}</h1>
<h:form id="appedit">
<p:panelGrid columns="3">
<h:outputText for="appkey" value="#{i18n['apiapp.appkey']}"/>
<p:inplace>
<f:facet name="output">
******** (Click to view and edit)
</f:facet>
<f:facet name="input">
<p:inputText size="30" id="appkey" redisplay="true" value="#{apiAppEditView.apiApp.applicationKey}"/>
</f:facet>
</p:inplace>
<h:message for="appkey"/>
<h:outputText for="appname" value="#{i18n['apiapp.name']}"/>
<p:inputText size="30" id="appname" value="#{apiAppEditView.apiApp.name}"/>
<h:message for="appname"/>
<h:outputText for="appdesc" value="#{i18n['apiapp.description']}"/>
<p:inputText size="30" id="appdesc" value="#{apiAppEditView.apiApp.description}"/>
<h:message for="appdesc"/>
</p:panelGrid>
<p:commandButton ajax="false" action="#{apiAppEditView.save}" value="#{i18n['apiapp.save']}"/>
</h:form>
<h2><h:outputText value="#{i18n['apiInstance.my.header']}"/></h2>
<p:commandButton value="#{i18n['apiInstance.create']}" action="#{apiAppEditView.initCreateInstance}" type="button" onclick="PF('createInstanceDlg').show();"/>
<p:dialog header="Create api instance" widgetVar="createInstanceDlg" closable="true" dynamic="true">
<h:form>
<p:panelGrid columns="3">
<h:outputText for="appinstevent" value="#{i18n['apiapp.event']}"/>
<h:outputText size="30" id="appinstevent" value="#{apiAppEditView.selectedInstance.eventuser.event.name}"/>
<h:message for="appinstevent"/>
<h:outputText for="appinstuser" value="#{i18n['apiapp.event']}"/>
<h:outputText size="30" id="appinstuser" value="(#{apiAppEditView.selectedInstance.eventuser.user.id}) #{apiAppEditView.selectedInstance.eventuser.user.wholeName}"/>
<h:message for="appinstuser"/>
<h:outputText for="appinstcreated" value="#{i18n['apiapp.created']}"/>
<h:outputText size="30" id="appinstcreated" value="#{apiAppEditView.selectedInstance.created}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}"/>
</h:outputText>
<h:message for="appinstcreated"/>
<h:outputText for="appinstenabled" value="#{i18n['apiapp.enabled']}"/>
<p:selectBooleanCheckbox id="appinstenabled" value="#{apiAppEditView.selectedInstance.enabled}"/>
<h:message for="appinstenabled"/>
<h:outputText for="appinstname" value="#{i18n['apiapp.name']}"/>
<p:inputText size="30" id="appinstname" value="#{apiAppEditView.selectedInstance.name}"/>
<h:message for="appinstname"/>
<h:outputText for="appinstnotes" value="#{i18n['apiapp.notes']}"/>
<p:inputText size="30" id="appinstnotes" value="#{apiAppEditView.selectedInstance.notes}"/>
<h:message for="appinstnotes"/>
<h:outputText for="appinstkey" value="#{i18n['apiapp.secretKey']}"/>
<p:inputText size="40" id="appinstkey" value="#{apiAppEditView.selectedInstance.secretKey}"/>
<h:message for="appinstkey"/>
</p:panelGrid>
<p:commandButton value="#{i18n['apiapp.save']}" action="#{apiAppEditView.saveInstance}"/>
</h:form>
</p:dialog>
<p:dataTable value="#{apiAppEditView.apiInstances}" var="instance">
<p:column width="80" headerText="#{i18n['apiInstance.enabled']}"> <h:outputText value="#{instance.enabled}"/> </p:column>
<p:column headerText="#{i18n['apiInstance.created']}"> <h:outputText value="#{instance.created}"/> </p:column>
<p:column headerText="#{i18n['apiIntance.name']}"> <h:outputText value="#{instance.name}"/> </p:column>
<p:column headerText="#{i18n['apiInstance.userWholename']}"> <h:outputText value="#{instance.eventuser.wholeName}"/> </p:column>
<p:column headerText="#{i18n['apiInstance.event']}"><h:outputText value="#{instance.eventuser.event.name}"/></p:column>
<p:column><p:commandButton value="#{i18n['apiInstance.edit']}" action="#{apiAppEditView.selectInstance}" oncomplete="PF('createInstanceDlg').show();"/></p:column>
</p:dataTable>
</ui:define>
</ui:composition>
</h:body>
</html>
\ No newline at end of file
<!DOCTYPE html <!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html" xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core" xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui"> xmlns:p="http://primefaces.org/ui">
<h:body> <h:body>
<ui:composition template="#{sessionHandler.template}"> <ui:composition template="#{sessionHandler.template}">
<f:metadata> <f:metadata>
<f:event type="preRenderView" <f:event type="preRenderView"
listener="#{applicationApiView.initApplicationListView}" /> listener="#{applicationApiView.initApplicationListView}"/>
</f:metadata> </f:metadata>
<ui:define name="content"> <ui:define name="content">
<button></button> <h:form>
<h:panelGrid columns="2">
<div style="display:none;" id="createApp"> <p:outputLabel for="newappName" value="#{i18n['apiapp.name']}" />
<p:inputText id="newappName" value="#{applicationApiView.newApplication.name}" required="true"/>
</div> </h:panelGrid>
<p:commandButton ajax="false" action="#{applicationApiView.createApp()}" value="#{i18n['apiapp.create']}"/>
</h:form>
<h1>#{i18n['apiapp.edit.applist']}</h1> <h1>#{i18n['apiapp.edit.applist']}</h1>
...@@ -27,20 +29,20 @@ ...@@ -27,20 +29,20 @@
<p:dataTable value="#{applicationApiView.applist}" var="app"> <p:dataTable value="#{applicationApiView.applist}" var="app">
<p:column headerText="#{i18n['apiapp.name']}"> <p:column headerText="#{i18n['apiapp.name']}">
<h:outputText value="#{app.name}" /> <h:link outcome="/api/edit?id=#{app.id}"><h:outputText value="#{app.name}"/></h:link>
</p:column> </p:column>
<p:column headerText="#{i18n['apiapp.description']"> <p:column headerText="#{i18n['apiapp.description']}">
<h:outputText value="#{app.description}" /> <h:outputText value="#{app.description}"/>
</p:column> </p:column>
<p:column> <p:column headerText="#{i18n['apiapp.created']}">
<h:outputText value="#{app.created}"> <h:outputText value="#{app.created}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" <f:convertDateTime pattern="#{sessionHandler.datetimeFormat}"
timeZone="#{sessionHandler.timezone}" /> timeZone="#{sessionHandler.timezone}"/>
</h:outputText> </h:outputText>
</p:column> </p:column>
<p:column headerText="#{i18n['apiapp.enabled']}"> <p:column headerText="#{i18n['apiapp.enabled']}">
<h:outputText value="#{app.enabled}" /> <h:outputText value="#{app.enabled}"/>
</p:column> </p:column>
</p:dataTable> </p:dataTable>
......
...@@ -14,51 +14,59 @@ ...@@ -14,51 +14,59 @@
<h:form> <h:form>
<h:panelGrid columns="3"> <h:panelGrid columns="3">
<h:outputLabel value="#{i18n['voting.create.name']}:" for="name" /> <p:outputLabel value="#{i18n['voting.create.name']}:" for="name" />
<h:inputText value="#{compoMgmtView.compo.name}" id="name" /> <p:inputText value="#{compoMgmtView.compo.name}" id="name" />
<h:message for="name" /> <p:message for="name" />
<h:outputLabel value="#{i18n['voting.create.description']}:" for="desc" /> <p:outputLabel value="#{i18n['voting.create.description']}:" for="desc" />
<h:inputText value="#{compoMgmtView.compo.description}" id="desc" /> <p:inputText value="#{compoMgmtView.compo.description}" id="desc" />
<h:message for="desc" /> <p:message for="desc" />
<h:outputLabel value="#{i18n['voting.create.maxParticipants']}:" for="maxPar" /> <p:outputLabel for="entrysubmitrole" value="#{i18n['voting.create.entrysubmitrole']}:" />
<h:inputText value="#{compoMgmtView.compo.maxParticipantCount}" id="maxPar" /> <p:selectOneMenu id="entrysubmitrole" value="#{compoMgmtView.compo.entrysubmitRole}" converter="#{roleConverter}">
<h:message for="maxPar" /> <f:selectItem itemLabel="----" />
<f:selectItems value="#{roleDataView.roleList}" var="r" itemLabel="#{r.name}" />
<h:outputLabel value="#{i18n['voting.create.holdVoting']}:" for="holdVoting" /> </p:selectOneMenu>
<h:selectBooleanCheckbox value="#{compoMgmtView.compo.holdVoting}" id="holdVoting" /> <p:message for="entrysubmitrole" />
<h:message for="holdVoting" />
<h:outputLabel value="#{i18n['voting.create.hidden']}:" for="hidden" /> <p:outputLabel value="#{i18n['voting.create.maxParticipants']}:" for="maxPar" />
<h:selectBooleanCheckbox value="#{compoMgmtView.compo.hidden}" id="hidden" /> <p:inputText value="#{compoMgmtView.compo.maxParticipantCount}" id="maxPar" />
<h:message for="hidden" /> <p:message for="maxPar" />
<h:outputLabel value="#{i18n['voting.create.compoStart']}:" for="cStart" /> <p:outputLabel value="#{i18n['voting.create.holdVoting']}:" for="holdVoting" />
<p:selectBooleanCheckbox value="#{compoMgmtView.compo.holdVoting}" id="holdVoting" />
<p:message for="holdVoting" />
<p:outputLabel value="#{i18n['voting.create.hidden']}:" for="hidden" />
<p:selectBooleanCheckbox value="#{compoMgmtView.compo.hidden}" id="hidden" />
<p:message for="hidden" />
<p: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" /> <p:calendar validator="#{votingDateValidator.saveCStart}" value="#{compoMgmtView.compo.startTime}" pattern="dd/MM/yyyy HH:mm" id="cStart" />
<h:message for="cStart" /> <p:message for="cStart" />
<h:outputLabel value="#{i18n['voting.create.compoEnd']}:" for="cEnd" /> <p: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" /> <p:calendar validator="#{votingDateValidator.validateCompo}" value="#{compoMgmtView.compo.endTime}" pattern="dd/MM/yyyy HH:mm" id="cEnd" />
<h:message for="cEnd" /> <p:message for="cEnd" />
<h:outputLabel value="#{i18n['voting.create.voteStart']}:" for="vStart" /> <p: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" /> <p:calendar validator="#{votingDateValidator.saveVStart}" value="#{compoMgmtView.compo.voteStart}" pattern="dd/MM/yyyy HH:mm" id="vStart" />
<h:message for="vStart" /> <p:message for="vStart" />
<h:outputLabel value="#{i18n['voting.create.voteEnd']}:" for="vEnd" /> <p: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" /> <p:calendar validator="#{votingDateValidator.validateVote}" value="#{compoMgmtView.compo.voteEnd}" pattern="dd/MM/yyyy HH:mm" id="vEnd" />
<h:message for="vEnd" /> <p:message for="vEnd" />
<h:outputLabel value="#{i18n['voting.create.submitStart']}:" for="sStart" /> <p: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" /> <p:calendar validator="#{votingDateValidator.saveSStart}" value="#{compoMgmtView.compo.submitStart}" pattern="dd/MM/yyyy HH:mm" id="sStart" />
<h:message for="sStart" /> <p:message for="sStart" />
<h:outputLabel value="#{i18n['voting.create.submitEnd']}:" for="sEnd" /> <p: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" /> <p:calendar validator="#{votingDateValidator.validateSubmit}" value="#{compoMgmtView.compo.submitEnd}" pattern="dd/MM/yyyy HH:mm" id="sEnd" />
<h:message for="sEnd" /> <p:message for="sEnd" />
<h:commandButton action="#{cc.attrs.commitAction}" id="commitbutton" value="#{cc.attrs.commitValue}" /> <p:commandButton ajax="false" action="#{cc.attrs.commitAction}" id="commitbutton" value="#{cc.attrs.commitValue}" />
</h:panelGrid> </h:panelGrid>
</h:form> </h:form>
......
...@@ -15,7 +15,6 @@ ...@@ -15,7 +15,6 @@
</composite:interface> </composite:interface>
<composite:implementation> <composite:implementation>
<h:outputScript library="primefaces" name="jquery/jquery.js" target="head" />
<p:panelGrid columns="2" columnClasses="topalign,topalign,topalign" styleClass="noBorders user_profile_page"> <p:panelGrid columns="2" columnClasses="topalign,topalign,topalign" styleClass="noBorders user_profile_page">
<h:form id="userform" enctype="multipart/form-data"> <h:form id="userform" enctype="multipart/form-data">
...@@ -158,13 +157,39 @@ ...@@ -158,13 +157,39 @@
</p:fieldset> </p:fieldset>
</h:form> </h:form>
<p:fieldset legend="#{i18n['user.meta.box.title']}" toggleable="true" collapsed="true" rendered="#{not empty userView.meta}"> <p:fieldset legend="#{i18n['user.meta.box.title']}" toggleable="true" collapsed="true" rendered="#{userView.metaAvailable}">
<div id="usermetaview"><pre><h:outputText value="#{userView.prettyMeta}" /></pre></div> <div id="usermetaview"><pre><h:outputText value="#{userView.prettyMeta}" /></pre></div>
</p:fieldset> </p:fieldset>
</p:panelGrid>
<p:fieldset toggleable="true" collapsed="true" legend="#{i18n['user.eventproperties']}" rendered="${!empty userEventPropertyView.properties}" style="max-width: 800px;">
<h:form id="eventpropertyview">
<p:growl id="msgs" showDetail="true"/>
<p:dataTable id="userpropertytable" widgetVar="userpropertytable" value="#{userEventPropertyView.properties}" var="property" editable="true" rowIndexVar="rowIndex">
</p:panelGrid> <p:ajax event="rowEdit" listener="#{userEventPropertyView.onRowEdit}" update="@form:msgs"/>
<p:ajax event="rowEditCancel" listener="#{userEventPropertyView.onRowCancel}" update="@form:msgs"/>
<p:column><h:outputText value="#{property.property.name.getValue(sessionStore.language)}" title="#{property.property.description.getValue(sessionStore.language)}"/></p:column>
<p:column>
<!--p:ajax event="save" listener="#{userEventPropertyView.saveProperty}" update="userpropertytable">
<f:setPropertyActionListener value="#{property}" target="#{userEventPropertyView.selectedProperty}"/>
</p:ajax-->
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{property.textvalue}"/></f:facet>
<f:facet name="input"><p:inputText onkeydown="PF('userpropertytable').onKeyDown(event)"
onkeyup="PF('userpropertytable').onKeyUp(event, #{rowIndex})"
value="#{property.textvalue}"
style="width:96%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:32px">
<p:rowEditor />
</p:column>
</p:dataTable>
</h:form>
</p:fieldset>
<p:fieldset toggleable="true" collapsed="true" legend="#{i18n['user.allergies']}"> <p:fieldset toggleable="true" collapsed="true" legend="#{i18n['user.allergies']}">
<h:form id="userAllergies"> <h:form id="userAllergies">
...@@ -178,20 +203,54 @@ ...@@ -178,20 +203,54 @@
</h:form> </h:form>
</p:fieldset> </p:fieldset>
<h:form id="userSelectableRoles"> <h:form id="userSelectableRoles">
<p:fieldset legend="#{i18n['user.userSelectableRoles']}" rendered="#{userView.showUserSelectableRoles and cc.attrs.showRoles}"> <p:fieldset legend="#{i18n['user.userSelectableRoles']}" rendered="#{userView.showUserSelectableRoles and cc.attrs.showRoles}">
<p:panelGrid columns="2" styleClass="noBorders"> <p:panelGrid columns="2" styleClass="noBorders">
<p:selectManyCheckbox converter="#{roleConverter}" layout="pageDirection" value="#{userView.userSelectableRoles}"> <p:selectManyCheckbox converter="#{roleConverter}" layout="pageDirection" value="#{userView.userSelectableRoles}">
<f:selectItems value="#{roleDataView.userSelectableRoles}" var="roleitem" itemLabel="#{roleitem.name}" itemValue="#{roleitem}" /> <f:selectItems value="#{roleDataView.userSelectableRoles}" var="roleitem" itemLabel="#{roleitem.name}" itemValue="#{roleitem}"/>
</p:selectManyCheckbox> </p:selectManyCheckbox>
</p:panelGrid> </p:panelGrid>
<p:commandButton update="userSelectableRoles" actionListener="#{userView.saveUserSelectableRoles}" value="#{i18n['user.saveUserSelectableRoles']}" /> <p:commandButton update="userSelectableRoles" actionListener="#{userView.saveUserSelectableRoles}" value="#{i18n['user.saveUserSelectableRoles']}"/>
<br /><h:outputText rendered="#{userView.saveSuccess}" styleClass="success" value="#{i18n['user.saveSuccessfull']}" /> <br/>
</p:fieldset> <h:outputText rendered="#{userView.saveSuccess}" styleClass="success" value="#{i18n['user.saveSuccessfull']}"/>
</h:form> </p:fieldset>
</h:form>
<script type="text/javascript">
$(function() {
$.extend(PF("userpropertytable"), {
onKeyDown : function(e) {
var key = e.which,
keyCode = $.ui.keyCode;
if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER)) {
e.preventDefault();
}
},
onKeyUp : function(e, rowIndex) {
var key = e.which,
keyCode = $.ui.keyCode;
if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER)) {
this.tbody
.find('.ui-row-editor .ui-icon-check')
.eq(rowIndex)
.click();
}
if (key === keyCode.ESCAPE) {
this.tbody
.find('.ui-row-editor .ui-icon-close')
.eq(rowIndex)
.click();
}
}
});
});
</script>
</composite:implementation> </composite:implementation>
</html> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"
xmlns:users="http://java.sun.com/jsf/composite/cditools/user" xmlns:tools="http://java.sun.com/jsf/composite/cditools" xmlns:account="http://java.sun.com/jsf/composite/cditools/account" xmlns:users="http://java.sun.com/jsf/composite/cditools/user" xmlns:tools="http://java.sun.com/jsf/composite/cditools" xmlns:account="http://java.sun.com/jsf/composite/cditools/account"
xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:p="http://primefaces.org/ui"> xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:p="http://primefaces.org/ui">
<h:body> <h:body>
<ui:composition template="#{sessionHandler.template}"> <ui:composition template="#{sessionHandler.template}">
<f:metadata> <f:metadata>
<f:viewParam name="userid" value="#{userView.userid}" /> <f:viewParam name="userid" value="#{userView.userid}"/>
<f:event type="preRenderView" listener="#{userView.initView}" /> <f:event type="preRenderView" listener="#{userView.initView}"/>
<f:event type="preRenderView" listener="#{userView.setCaptureForwardUrl('')}" /> <f:event type="preRenderView" listener="#{userView.setCaptureForwardUrl('')}"/>
</f:metadata> </f:metadata>
<ui:define name="title"> <ui:define name="title">
...@@ -16,27 +16,43 @@ ...@@ -16,27 +16,43 @@
<!-- <users:usertabs tabId="edit" /> --> <!-- <users:usertabs tabId="edit" /> -->
</ui:define> </ui:define>
<ui:define name="edittab"> <ui:define name="edittab">
<users:usertabs tabId="edit" /> <users:usertabs tabId="edit"/>
</ui:define> </ui:define>
<ui:define name="content"> <ui:define name="content">
<users:edit commitaction="#{userCartView.saveUser()}" commitvalue="#{i18n['user.save']}" />
<h:form id="roleform" rendered="#{roleView.canReadRoles}"> <users:edit commitaction="#{userCartView.saveUser()}" commitvalue="#{i18n['user.save']}"/>
<h2> <div style="display: flex;">
<h:outputText value="#{i18n['user.roles']}:" /> <h:form id="roleform" rendered="#{roleView.canReadRoles}">
</h2>
<h:selectManyCheckbox converter="#{roleConverter}" disabled="#{!roleView.canWriteRoles}" layout="pageDirection" id="roles" value="#{userView.usersRoles}">
<f:selectItems var="roleitem" itemLabel="#{roleitem.name}" value="#{roleDataView.roles}" />
</h:selectManyCheckbox>
<div>
<h:message rendered="#{roleView.canReadRoles}" for="roles" />
</div>
<h:commandButton action="#{userView.saveRoles}" value="#{i18n['user.saveRoles']}" />
<h2>
</h:form> <h:outputText value="#{i18n['user.roles']}:"/>
</h2>
<h:selectManyCheckbox converter="#{roleConverter}" disabled="#{!roleView.canWriteRoles}" layout="pageDirection" id="roles" value="#{userView.usersRoles}">
<f:selectItems var="roleitem" itemLabel="#{roleitem.name}" value="#{roleDataView.roles}"/>
</h:selectManyCheckbox>
<div>
<p:message rendered="#{roleView.canReadRoles}" for="roles"/>
</div>
<p:commandButton ajax="false" action="#{userView.saveRoles}" value="#{i18n['user.saveRoles']}"/>
</h:form>
<ui:fragment rendered="#{roleView.canReadRoles}">
<div style="margin-left: 4em;">
<h2><h:outputText value="#{i18n['user.allroles']}"/></h2>
<p:dataTable style="max-width: 600px;" var="r" value="#{userView.allUsersRoles}">
<p:column style="width: 30%;"><f:facet name="header"><h:outputText value="#{i18n['role.name']}"/></f:facet><h:outputText value="#{r.key.name}"/></p:column>
<p:column>
<f:facet name="header">
<h:outputText value="#{i18n['role.source']}"/>
</f:facet>
<ul><ui:repeat var="src" value="#{r.value}">
<li>#{i18n['role.source.'+=src]}</li>
</ui:repeat></ul>
</p:column>
</p:dataTable>
</div>
</ui:fragment>
</div>
</ui:define> </ui:define>
</ui:composition> </ui:composition>
</h:body> </h:body>
......
<!DOCTYPE html <!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:users="http://java.sun.com/jsf/composite/cditools/user" <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:users="http://java.sun.com/jsf/composite/cditools/user"
xmlns:tools="http://java.sun.com/jsf/composite/cditools" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> xmlns:tools="http://java.sun.com/jsf/composite/cditools" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
<h:body> <h:body>
<ui:composition template="#{sessionHandler.template}"> <ui:composition template="#{sessionHandler.template}">
<f:metadata> <f:metadata>
<f:event type="preRenderView" listener="#{compoView.initAdminListView()}" /> <f:event type="preRenderView" listener="#{compoView.initAdminListView()}"/>
</f:metadata> </f:metadata>
<ui:define name="content"> <ui:define name="content">
<h:form id="admincompolist" styleClass="moya_datatable2"> <h:form id="admincompolist" styleClass="moya_datatable2">
<h1>#{i18n['voting.allcompos.header']}</h1> <h1>#{i18n['voting.allcompos.header']}</h1>
<p>#{i18n['voting.allcompos.description']}</p> <p>#{i18n['voting.allcompos.description']}</p>
<p:dataTable styleClass="bordertable" rowClasses="roweven,rowodd" id="compolisttable" value="#{compoView.compos}" var="compo"> <p:dataTable styleClass="bordertable" rowClasses="roweven,rowodd" id="compolisttable" value="#{compoView.compos}" var="compo">
<p:column headerText="#{i18n['voting.allcompos.name']}"> <p:column headerText="#{i18n['voting.allcompos.name']}">
<h:outputText value="#{compo.name}" /> <h:outputText value="#{compo.compo.name}"/>
</p:column> </p:column>
<!-- <h:column rendered="#{compoView.curEntries}"> --> <!-- <h:column rendered="#{compoView.curEntries}"> -->
...@@ -30,41 +30,40 @@ ...@@ -30,41 +30,40 @@
<!-- <f:facet name="header"> --> <!-- <f:facet name="header"> -->
<!-- <h:outputText value="#{i18n['voting.allcompos.maxParts']}" /> --> <!-- <h:outputText value="#{i18n['voting.allcompos.maxParts']}" /> -->
<!-- </f:facet> --> <!-- </f:facet> -->
<!-- <h:outputText value="#{compo.maxParticipantCount}" /> --> <!-- <h:outputText value="#{compo.compo.maxParticipantCount}" /> -->
<!-- </h:column> --> <!-- </h:column> -->
<p:column headerText="#{i18n['voting.allcompos.startTime']}"> <p:column headerText="#{i18n['voting.allcompos.startTime']}">
<h:outputText value="#{compo.startTime.time}"> <h:outputText value="#{compo.compo.startTime.time}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" /> <f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}"/>
</h:outputText> </h:outputText>
</p:column> </p:column>
<p:column headerText="#{i18n['voting.allcompos.voteEnd']}"> <p:column headerText="#{i18n['voting.allcompos.voteEnd']}">
<h:outputText value="#{compo.voteEnd.time}"> <h:outputText value="#{compo.compo.voteEnd.time}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" /> <f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}"/>
</h:outputText> </h:outputText>
</p:column> </p:column>
<p:column headerText="#{i18n['voting.allcompos.submitEnd']}"> <p:column headerText="#{i18n['voting.allcompos.submitEnd']}">
<h:outputText value="#{compo.submitEnd.time}"> <h:outputText value="#{compo.compo.submitEnd.time}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" /> <f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}"/>
</h:outputText> </h:outputText>
</p:column> </p:column>
<p:column headerText="#{i18n['voting.allcompos.holdVoting']}"> <p:column headerText="#{i18n['voting.allcompos.holdVoting']}">
<h:outputText value="#{compo.holdVoting}" /> <h:outputText value="#{compo.compo.holdVoting}"/>
</p:column> </p:column>
<p:column headerText="#{i18n['voting.allcompos.hidden']}"> <p:column headerText="#{i18n['voting.allcompos.hidden']}">
<h:outputText value="#{compo.hidden}" /> <h:outputText value="#{compo.compo.hidden}"/>
</p:column> </p:column>
<p:column> <p:column>
<h:commandButton rendered="#{compo.vote or compoView.manage}" action="#{compoView.startVote()}" value="#{i18n['voting.compo.vote']}" /> <p:commandButton ajax="false" action="#{compoView.startVote()}" value="#{i18n['voting.compo.vote']}"/><br/>
</p:column> <p:link rendered="#{compo.canSubmit}" outcome="/voting/submitEntry" value="#{i18n['voting.compo.submit']}">
<p:column> <f:param name="compoId" value="#{compo.compo.id}"/>
<h:commandButton rendered="#{compo.submit or compoView.manage}" action="#{compoView.submitEntry()}" value="#{i18n['voting.compo.submit']}" /> </p:link>
</p:column> </p:column>
<p:column rendered="#{compoView.manage}"> <p:column rendered="#{compoView.manage}">
<h:link outcome="details" value="#{i18n['compo.edit']}"> <h:link outcome="details" value="#{i18n['compo.edit']}">
<f:param name="compoId" value="#{compo.id}" /> <f:param name="compoId" value="#{compo.compo.id}"/>
</h:link> </h:link>
</p:column> </p:column>
</p:dataTable> </p:dataTable>
......
...@@ -10,70 +10,69 @@ ...@@ -10,70 +10,69 @@
<f:event type="preRenderView" listener="#{compoView.initListView()}" /> <f:event type="preRenderView" listener="#{compoView.initListView()}" />
</f:metadata> </f:metadata>
<ui:define name="content"> <ui:define name="content">
<h:outputStylesheet library="style" name="insomnia2/css/actionlog.css" />
<h1>#{i18n['voting.allcompos.header']}</h1>
<p>#{i18n['voting.allcompos.description']}</p>
<h1>#{i18n['voting.allcompos.header']}</h1>
<h:form id="compolist" styleClass="moya_datatable2"> <h:form id="compolist" styleClass="moya_datatable2">
<h:dataTable styleClass="bordertable" rowClasses="roweven,rowodd" id="compolisttable" value="#{compoView.compos}" var="compo"> <p:dataTable styleClass="bordertable" tableStyle="width: auto;" rowClasses="roweven,rowodd" id="compolisttable" value="#{compoView.compos}" var="compo">
<h:column> <p:column>
<f:facet name="header"> <f:facet name="header">
<h:outputText value="#{i18n['voting.allcompos.name']}" /> <h:outputText value="#{i18n['voting.allcompos.name']}" />
</f:facet> </f:facet>
<h:outputText value="#{compo.name}" /> <h:outputText value="#{compo.compo.name}" />
</h:column> </p:column>
<!-- <h:column rendered="#{compoView.curEntries}"> --> <!-- <p:column rendered="#{compoView.curEntries}"> -->
<!-- <f:facet name="header"> --> <!-- <f:facet name="header"> -->
<!-- <h:outputText value="#{i18n['voting.allcompos.curEntries']}" /> --> <!-- <h:outputText value="#{i18n['voting.allcompos.curEntries']}" /> -->
<!-- </f:facet> --> <!-- </f:facet> -->
<!-- <h:outputText value="#{compoEntries.size()}" /> --> <!-- <h:outputText value="#{compoEntries.size()}" /> -->
<!-- </h:column> --> <!-- </p:column> -->
<!-- <h:column rendered="#{compoView.maxParts}"> --> <!-- <p:column rendered="#{compoView.maxParts}"> -->
<!-- <f:facet name="header"> --> <!-- <f:facet name="header"> -->
<!-- <h:outputText value="#{i18n['voting.allcompos.maxParts']}" /> --> <!-- <h:outputText value="#{i18n['voting.allcompos.maxParts']}" /> -->
<!-- </f:facet> --> <!-- </f:facet> -->
<!-- <h:outputText value="#{compo.maxParticipantCount}" /> --> <!-- <h:outputText value="#{compo.maxParticipantCount}" /> -->
<!-- </h:column> --> <!-- </p:column> -->
<h:column> <p:column>
<f:facet name="header"> <f:facet name="header">
<h:outputText value="#{i18n['voting.allcompos.startTime']}" /> <h:outputText value="#{i18n['voting.allcompos.startTime']}" />
</f:facet> </f:facet>
<h:outputText value="#{compo.startTime.time}"> <h:outputText value="#{compo.compo.startTime.time}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" /> <f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
</h:outputText> </h:outputText>
</h:column> </p:column>
<h:column> <p:column>
<f:facet name="header"> <f:facet name="header">
<h:outputText value="#{i18n['voting.allcompos.voteEnd']}" /> <h:outputText value="#{i18n['voting.allcompos.voteEnd']}" />
</f:facet> </f:facet>
<h:outputText value="#{compo.voteEnd.time}"> <h:outputText value="#{compo.compo.voteEnd.time}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" /> <f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
</h:outputText> </h:outputText>
</h:column> </p:column>
<h:column> <p:column>
<f:facet name="header"> <f:facet name="header">
<h:outputText value="#{i18n['voting.allcompos.submitEnd']}" /> <h:outputText value="#{i18n['voting.allcompos.submitEnd']}" />
</f:facet> </f:facet>
<h:outputText value="#{compo.submitEnd.time}"> <h:outputText value="#{compo.compo.submitEnd.time}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" /> <f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}" />
</h:outputText> </h:outputText>
</h:column> </p:column>
<h:column>
<h:commandButton rendered="#{compo.vote or compoView.manage}" action="#{compoView.startVote()}" value="#{i18n['voting.compo.vote']}" /> <p:column>
</h:column> <p:commandButton rendered="#{compo.canVote}" action="#{compoView.startVote()}" value="#{i18n['voting.compo.vote']}" />
<h:column> <p:link rendered="#{compo.canSubmit}" outcome="/voting/submitEntry" value="#{i18n['voting.compo.submit']}" >
<h:commandButton rendered="#{compo.submit or compoView.manage}" action="#{compoView.submitEntry()}" value="#{i18n['voting.compo.submit']}" /> <f:param name="compoId" value="#{compo.compo.id}" />
</p:link>
</h:column> </p:column>
<h:column rendered="#{compoView.manage}"> <p:column rendered="#{compoView.manage}">
<h:link outcome="details" value="#{i18n['compo.edit']}"> <h:link outcome="details" value="#{i18n['compo.edit']}">
<f:param name="compoId" value="#{compo.id}" /> <f:param name="compoId" value="#{compo.compo.id}" />
</h:link> </h:link>
</h:column> </p:column>
</h:dataTable> </p:dataTable>
</h:form> </h:form>
......
<!DOCTYPE html <!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:users="http://java.sun.com/jsf/composite/cditools/user" <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:users="http://java.sun.com/jsf/composite/cditools/user"
xmlns:compo="http://java.sun.com/jsf/composite/cditools/compo" xmlns:tools="http://java.sun.com/jsf/composite/cditools" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> xmlns:compo="http://java.sun.com/jsf/composite/cditools/compo" xmlns:tools="http://java.sun.com/jsf/composite/cditools" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
<h:body> <h:body>
<ui:composition template="#{sessionHandler.template}"> <ui:composition template="#{sessionHandler.template}">
<f:metadata> <f:metadata>
<f:viewParam name="compoId" value="#{compoMgmtView.compoId}" /> <f:viewParam name="compoId" value="#{compoMgmtView.compoId}"/>
<!-- <f:viewParam name="compoId" value="#{compoMgmtView.compoId2}" /> --> <!-- <f:viewParam name="compoId" value="#{compoMgmtView.compoId2}" /> -->
<f:event type="preRenderView" listener="#{compoMgmtView.initView}" /> <f:event type="preRenderView" listener="#{compoMgmtView.initView}"/>
</f:metadata> </f:metadata>
<ui:define name="content"> <ui:define name="content">
<!-- <h:outputStylesheet library="style" name="insomnia2/css/actionlog.css" /> --> <!-- <h:outputStylesheet library="style" name="insomnia2/css/actionlog.css" /> -->
<h1>Compo: #{compoMgmtView.compo.name}</h1> <h1>Compo: #{compoMgmtView.compo.name}</h1>
<p>Infoa compon entryistä</p> <p>Infoa compon entryistä</p>
<compo:editCompo commitAction="#{compoMgmtView.saveCompo}" commitValue="#{i18n['voting.create.saveCompo']}" /> <compo:editCompo commitAction="#{compoMgmtView.saveCompo}" commitValue="#{i18n['voting.create.saveCompo']}"/>
<h2>#{i18n['compoMgmtView.compo.entries']}</h2> <h2>Compo filetypes</h2>
<h:form id="filetypeEditform">
<h:form> <p:panelGrid columns="2">
<p:dataTable styleClass="bordertable" rowClasses="roweven,rowodd" id="compolisttable" value="#{compoMgmtView.entries}" var="entry"> <p:outputLabel for="filetypeid" rendered="#{not empty compoMgmtView.filetype.id}" value="#{i18n['compo.filetype.id']}"/>
<p:column headerText="Title"> <h:outputText id="filetypeid" rendered="#{not empty compoMgmtView.filetype.id}" value="#{compoMgmtView.filetype.id}"/>
<h:outputText value="#{entry.title}" />
</p:column> <p:outputLabel for="filetypename" value="#{i18n['compo.filetype.name']}"/>
<p:column headerText="Author"> <p:inputText id="filetypename" value="#{compoMgmtView.filetype.name}"/>
<h:outputText value="#{entry.author}" />
</p:column> <p:outputLabel for="filetypesort" value="#{i18n['compo.filetype.sort']}"/>
<p:column headerText="Notes"> <p:inputText id="filetypesort" value="#{compoMgmtView.filetype.sort}"/>
<h:outputText value="#{entry.notes}" />
</p:column> <p:outputLabel for="filetypetype" value="#{i18n['compo.filetype.filetype']}"/>
<p:column headerText="Screenmessage"> <p:selectOneMenu id="filetypetype" value="#{compoMgmtView.filetype.filetype}">
<h:outputText value="#{entry.screenMessage}" /> <f:selectItems value="#{compoMgmtView.filetypeTypes}" val="t"/>
</p:column> </p:selectOneMenu>
<p:column headerText="creator"> </p:panelGrid>
<h:link outcome="/useradmin/edit" value="#{entry.creator.user.nick}"> <p:commandButton update="filetypelist,filetypeEditform" action="#{compoMgmtView.saveFiletype}" value="#{i18n['save']}"/>
<f:param name="userid" value="#{entry.creator.user.id}" /> </h:form>
</h:link> <br/>
</p:column>
<p:column headerText="Sort"> <p:dataTable id="filetypelist" value="#{compoMgmtView.compo.filetypes}" var="ft">
<h:inputText value="#{entry.sort}" size="4" /> <p:column> <h:outputText value="#{ft.name}"/> </p:column>
</p:column> <p:column> <h:outputText value="#{ft.filetype}"/> </p:column>
<p:column headerText="Vote total"> <p:column>
<h:outputText value="#{entry.votetotal}" /> <p:commandButton value="Edit" update="filetypeEditform" action="#{compoMgmtView.editFiletype(ft.id)}" />
</p:column> &nbsp;<p:commandButton value="Delete" update="filetypelist" action="#{compoMgmtView.deleteFiletype(ft.id)}" />
<p:column headerText="Vote count">
<h:outputText value="#{entry.votes.size()}" /> </p:column>
</p:column>
</p:dataTable>
<p:column>
<h:link outcome="/voting/submitEntry" value="#{i18n['entry.edit']}"> <h2>#{i18n['compoMgmtView.compo.entries']}</h2>
<f:param name="entryId" value="#{entry.id}" />
</h:link> <h:form>
</p:column> <p:dataTable styleClass="bordertable" rowClasses="roweven,rowodd" id="compolisttable" value="#{compoMgmtView.entries}" var="entry">
<p:column headerText="Title">
</p:dataTable> <h:outputText value="#{entry.title}"/>
<h:commandButton action="#{compoMgmtView.saveSort}" value="#{i18n['compo.savesort']}" /> </p:column>
</h:form> <p:column headerText="Author">
<h:outputText value="#{entry.author}"/>
</p:column>
</ui:define> <p:column headerText="Notes">
</ui:composition> <h:outputText value="#{entry.notes}"/>
</h:body> </p:column>
<p:column headerText="Screenmessage">
<h:outputText value="#{entry.screenMessage}"/>
</p:column>
<p:column headerText="creator">
<h:link outcome="/useradmin/edit" value="#{entry.creator.user.nick}">
<f:param name="userid" value="#{entry.creator.user.id}"/>
</h:link>
</p:column>
<p:column headerText="Sort">
<h:inputText value="#{entry.sort}" size="4"/>
</p:column>
<p:column headerText="Vote total">
<h:outputText value="#{entry.votetotal}"/>
</p:column>
<p:column headerText="Vote count">
<h:outputText value="#{entry.votes.size()}"/>
</p:column>
<p:column>
<h:link outcome="/voting/submitEntry" value="#{i18n['entry.edit']}">
<f:param name="entryId" value="#{entry.id}"/>
</h:link>
</p:column>
</p:dataTable>
<p:commandButton ajax="false" action="#{compoMgmtView.saveSort}" value="#{i18n['compo.savesort']}"/>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html> </html>
\ No newline at end of file
<!DOCTYPE html <!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:users="http://java.sun.com/jsf/composite/cditools/user" <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:users="http://java.sun.com/jsf/composite/cditools/user"
xmlns:tools="http://java.sun.com/jsf/composite/cditools" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> xmlns:tools="http://java.sun.com/jsf/composite/cditools" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
<h:body> <h:body>
<ui:composition template="#{sessionHandler.template}"> <ui:composition template="#{sessionHandler.template}">
<f:metadata> <f:metadata>
<f:event type="preRenderView" listener="#{voteListView.initView}" /> <f:event type="preRenderView" listener="#{voteListView.initView}" />
</f:metadata> </f:metadata>
<ui:define name="content"> <ui:define name="content">
<h1>My entries</h1> <h1>My entries</h1>
<h:form id="myEntries" styleClass="moya_datatable2"> <h:form id="myEntries" styleClass="moya_datatable2">
<h:dataTable styleClass="bordertable" rowClasses="roweven,rowodd" id="compolisttable" value="#{voteListView.entries}" var="entry"> <p:dataTable tableStyle="width: auto;" styleClass="bordertable" rowClasses="roweven,rowodd" id="compolisttable" value="#{voteListView.entries}" var="entry">
<h:column> <p:column headerText="Title">
<f:facet name="header"> <h:outputText value="#{entry.title}" />
<h:outputText value="Title" /> </p:column>
</f:facet> <p:column headerText="Author">
<h:outputText value="#{entry.title}" /> <h:outputText value="#{entry.author}" />
</h:column> </p:column>
<h:column> <p:column headerText="Notes">
<f:facet name="header"> <h:outputText value="#{entry.notes}" />
<h:outputText value="Author" /> </p:column>
</f:facet> <p:column headerText="Screen message">
<h:outputText value="#{entry.author}" /> <h:outputText value="#{entry.screenMessage}" />
</h:column> </p:column>
<h:column>
<f:facet name="header"> <p:column>
<h:outputText value="Notes" /> <h:link outcome="/voting/submitEntry" value="#{i18n['entry.edit']}">
</f:facet> <f:param name="entryId" value="#{entry.id}" />
<h:outputText value="#{entry.notes}" /> </h:link>
</h:column> </p:column>
<h:column>
<f:facet name="header"> </p:dataTable>
<h:outputText value="Screen message" />
</f:facet> </h:form>
<h:outputText value="#{entry.screenMessage}" />
</h:column>
</ui:define>
<h:column> </ui:composition>
<h:link outcome="/voting/submitEntry" value="#{i18n['entry.edit']}"> </h:body>
<f:param name="entryId" value="#{entry.id}" />
</h:link>
</h:column>
</h:dataTable>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html> </html>
\ No newline at end of file
<!DOCTYPE html <!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:users="http://java.sun.com/jsf/composite/cditools/user" <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:users="http://java.sun.com/jsf/composite/cditools/user"
xmlns:tools="http://java.sun.com/jsf/composite/cditools" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> xmlns:tools="http://java.sun.com/jsf/composite/cditools" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
<h:body> <h:body>
<ui:composition template="#{sessionHandler.template}"> <ui:composition template="#{sessionHandler.template}">
<f:metadata> <f:metadata>
<f:viewParam name="compoId" value="#{compoView.compoId}" /> <f:viewParam name="compoId" value="#{entryEditView.compoId}"/>
<f:viewParam name="entryId" value="#{compoView.entryId}" /> <f:viewParam name="entryId" value="#{entryEditView.entryId}"/>
<f:event type="preRenderView" listener="#{compoView.initEntryView}" /> <f:event type="preRenderView" listener="#{entryEditView.initEntryView}"/>
</f:metadata> </f:metadata>
<ui:define name="content"> <ui:define name="content">
<!-- <h:outputStylesheet library="style" name="insomnia2/css/actionlog.css" /> --> <!-- <h:outputStylesheet library="style" name="insomnia2/css/actionlog.css" /> -->
<h1>#{i18n['voting.compoentryadd.title']}</h1> <h1>#{i18n['voting.compoentryadd.title']}</h1>
<p> <p>
#{i18n['voting.compoentryadd.description']} #{i18n['voting.compoentryadd.description']}
<h:outputText value="#{compoView.compo.name}" /> <h:outputText value="#{entryEditView.compo.name}"/>
</p> </p>
<p> <p>
<h:outputText value="#{compoView.compo.description}" /> <h:outputText value="#{entryEditView.compo.description}"/>
</p> </p>
<h:form> <h:form>
<h:panelGrid columns="3"> <h:outputText value="#{entryEditView.entry.id}"/>
<h:outputLabel value="Title" for="name" /> <h:panelGrid columns="3">
<h:inputText value="#{compoView.entry.title}" id="name" /> <h:outputLabel value="Title" for="name"/>
<h:message for="name" /> <p:inputText value="#{entryEditView.entry.title}" id="name"/>
<h:message for="name"/>
<h:outputLabel value="Author" for="author" />
<h:inputText value="#{compoView.entry.author}" id="author" /> <h:outputLabel value="Author" for="author"/>
<h:message for="author" /> <p:inputText value="#{entryEditView.entry.author}" id="author"/>
<h:message for="author"/>
<h:outputLabel value="#{i18n['voting.compoentryadd.notes']}" for="notes" />
<h:inputTextarea value="#{compoView.entry.notes}" id="notes" /> <h:outputLabel value="#{i18n['voting.compoentryadd.notes']}" for="notes"/>
<h:message for="notes" /> <p:inputTextarea value="#{entryEditView.entry.notes}" id="notes"/>
<h:message for="notes"/>
<h:outputLabel value="#{i18n['voting.compoentryadd.screenmessage']}" for="screenmessage" />
<h:inputTextarea value="#{compoView.entry.screenMessage}" id="screenmessage" /> <h:outputLabel value="#{i18n['voting.compoentryadd.screenmessage']}" for="screenmessage"/>
<h:message for="screenmessage" /> <p:inputTextarea value="#{entryEditView.entry.screenMessage}" id="screenmessage"/>
<h:commandButton rendered="#{empty compoView.entry.id}" action="#{compoView.createEntry()}" value="#{i18n['voting.compoentryadd.button']}" /> <h:message for="screenmessage"/>
<h:commandButton rendered="#{!empty compoView.entry.id}" action="#{compoView.saveEntry()}" value="#{i18n['voting.compoentrysave.button']}" />
</h:panelGrid>
</h:panelGrid> <p:commandButton ajax="false" rendered="#{empty entryEditView.entry.id}" action="#{entryEditView.createEntry()}" value="#{i18n['voting.compoentryadd.button']}"/>
<p:commandButton ajax="false" rendered="#{not empty entryEditView.entry.id}" action="#{entryEditView.saveEntry()}" value="#{i18n['voting.compoentrysave.button']}"/>
</h:form>
<h:commandButton rendered="#{empty compoView.entry.id}" action="#{compoView.createEntry()}" value="Ilmoittaudu kilpailuun" />
</h:form> <ui:fragment rendered="#{!empty entryEditView.entry.id}">
<h2>
<ui:fragment rendered="#{!empty compoView.entry.id}"> <h:outputText value="#{i18n['compofile.download.header']}"/>
<h:form enctype="multipart/form-data"> </h2>
<p:fileUpload value="#{compoView.uploadedFile}" id="uploadedfile" mode="simple" />
<h:commandButton action="#{compoView.submitEntryfile}" value="#{i18n['compofile.upload']}" /> <p:dataTable style="width: auto;" value="#{entryEditView.entryFiletypes}" var="ft">
</h:form> <p:column headerText="">
<h:form rendered="#{!empty compoFileDownloadView.files}"> <h:outputText value="#{ft.filetype.name}"/>
<h2> </p:column>
<h:outputText value="#{i18n['compofile.download.header']}" /> <p:column headerText="Current file">
</h2> <p:commandButton rendered="#{not empty ft.entryfiletype.currentFile}" update=":fileInfoForm:fileInfoDialog" oncomplete="PF('fileInfoDialog').show()" icon="ui-icon-search"
<p:dataTable value="#{compoFileDownloadView.files}" var="fi"> title="View files">
<p:column headerText="#{i18n['compofile.fileName']}"> <f:setPropertyActionListener value="#{ft.entryfiletype}" target="#{entryEditView.selectedFiletype}"/>
<h:outputText value="#{fi.fileName}" /> </p:commandButton>
</p:column> </p:column>
<p:column headerText="#{i18n['compofile.uploadTime']}"> <p:column>
<h:outputText value="#{fi.uploaded.time}"> <form id="filesubmit-#{ft.filetype.id}" action="#{request.contextPath}/EntryFile" method="post" enctype="multipart/form-data">
<f:convertDateTime pattern="#{sessionHandler.shortDatetimeFormat}" /> <div>
</h:outputText> <input type="file" name="file"/>
</p:column> <input type="hidden" name="entryId" value="#{entryEditView.entry.id}"/>
<p:column headerText="#{i18n['compofile.shaChecksum']}"> <input type="hidden" name="typeId" value="#{ft.filetype.id}"/>
<h:outputText value="#{fi.hash}" />
</p:column> <button type="submit">Submit</button>
<p:column> </div>
<p:commandButton ajax="false" value="#{i18n['compofile.download']}" actionListener="#{compoFileDownloadView.selectDownloadedFile}"> </form>
<p:fileDownload value="#{compoFileDownloadView.dlfile}" /> </p:column>
</p:commandButton> </p:dataTable>
</p:column>
</p:dataTable> <h:form id="fileInfoForm">
</h:form> <p:dialog id="fileInfoDialog" widgetVar="fileInfoDialog" modal="true" appendTo="@(body)">
</ui:fragment>
<p:dataTable tableStyle="width: auto;" value="#{entryEditView.selectedFiletype.entryFiles}" var="file">
</ui:define> <p:column headerText="CurrentFile">
</ui:composition> <h:outputText value="X" rendered="#{entryEditView.selectedFiletype.currentFile==file}"/>
</h:body> </p:column>
<p:column headerText="#{i18n['compofile.fileName']}">
<a href="#{request.contextPath}/EntryFile/#{file.id}">
<h:outputText value="#{file.fileName}"/>
</a>
</p:column>
<p:column headerText="#{i18n['compofile.uploadTime']}">
<h:outputText value="#{file.uploaded}">
<f:convertDateTime pattern="#{sessionHandler.datetimeFormat}" timeZone="#{sessionHandler.timezone}"/>
</h:outputText>
</p:column>
<p:column headerText="#{i18n['compofile.shaChecksum']}">
<h:outputText value="#{file.hash}"/>
</p:column>
</p:dataTable>
</p:dialog>
</h:form>
<!--
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{compoView.uploadedFile}" id="uploadedfile" mode="simple"/>
<p:commandButton ajax="false" action="#{compoView.submitEntryfile}" value="#{i18n['compofile.upload']}"/>
</h:form>
<br/>
<h:form rendered="#{!empty compoFileDownloadView.files}">
<p:dataTable value="#{compoView.compo.filetypes}" var="type">
<p:column> <h:outputText value="#{type.name}"/> </p:column>
<p:column> <h:outputText value="#{type.filetype}"/> </p:column>
</p:dataTable>
<p:dataTable value="#{compoFileDownloadView.files}" var="fi">
<p:column headerText="#{i18n['compofile.fileName']}">
<h:outputText value="#{fi.fileName}"/>
</p:column>
<p:column headerText="#{i18n['compofile.uploadTime']}">
<h:outputText value="#{fi.uploaded.time}"> <f:convertDateTime pattern="#{sessionHandler.shortDatetimeFormat}"/> </h:outputText>
</p:column>
<p:column headerText="#{i18n['compofile.shaChecksum']}">
<h:outputText value="#{fi.hash}"/>
</p:column>
<p:column>
<p:commandButton ajax="false" value="#{i18n['compofile.download']}" actionListener="#{compoFileDownloadView.selectDownloadedFile}">
<p:fileDownload value="#{compoFileDownloadView.dlfile}"/>
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
-->
</ui:fragment>
</ui:define>
</ui:composition>
</h:body>
</html> </html>
\ No newline at end of file
...@@ -20,6 +20,7 @@ package fi.codecrew.moya; ...@@ -20,6 +20,7 @@ package fi.codecrew.moya;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.Principal; import java.security.Principal;
import java.util.Base64; import java.util.Base64;
...@@ -179,13 +180,13 @@ public class HostnameFilter implements Filter { ...@@ -179,13 +180,13 @@ public class HostnameFilter implements Filter {
if (httpRequest.getUserPrincipal() == null) { if (httpRequest.getUserPrincipal() == null) {
// Check if we are can login in with rest alternative methods ( appkey, basic auth, etc.. ) // Check if we are can login in with rest alternative methods ( appkey, basic auth, etc.. )
if (RestApplicationEntrypoint.REST_PATH.equals(httpRequest.getServletPath()) if (RestApplicationEntrypoint.REST_PATH.equals(httpRequest.getServletPath())
|| "/dydata".equals(httpRequest.getServletPath())) { || "/dydata".equals(httpRequest.getServletPath()) || "/graphql".equals(httpRequest.getServletPath())) {
authtype = AuthType.REST; authtype = AuthType.REST;
if (!restAuth(httpRequest, response) && RestApplicationEntrypoint.REST_PATH.equals(httpRequest.getServletPath())) { if (!restAuth(httpRequest, response) && RestApplicationEntrypoint.REST_PATH.equals(httpRequest.getServletPath())) {
response.reset(); response.reset();
response.getOutputStream().write("Rest auth failed! ".getBytes( Charsets.UTF_8)); response.getOutputStream().write("Rest auth failed! ".getBytes( StandardCharsets.UTF_8));
if (response instanceof HttpServletResponse) { if (response instanceof HttpServletResponse) {
HttpServletResponse httpResp = (HttpServletResponse) response; HttpServletResponse httpResp = (HttpServletResponse) response;
......
package fi.codecrew.moya.graphql;
public class AlreadyBuiltException extends RuntimeException {
public AlreadyBuiltException(String s) {
super(s);
}
}
package fi.codecrew.moya.graphql;
import graphql.schema.*;
import javax.persistence.metamodel.Attribute;
import javax.persistence.metamodel.PluralAttribute;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.*;
import static graphql.Scalars.*;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
import static graphql.schema.GraphQLObjectType.newObject;
public class EntityGQLBuilder<T> implements GQLEntityContainer {
private final GraphQLObjectType.Builder builder;
private final GraphQLBuilder parent;
private final String typeName;
private final List<GraphQLFieldDefinition.Builder> fields = new ArrayList<>();
private GraphQLObjectType builtObject;
public EntityGQLBuilder(String name, GraphQLBuilder bld) {
this.typeName = name;
this.parent = bld;
this.builder = newObject().name(name);
}
public GraphQLFieldDefinition.Builder addField(GraphQLOutputType type) {
return addField()
.type(type)
.name(type.getName().toLowerCase());
}
public GraphQLFieldDefinition.Builder addField() {
if (builtObject != null) {
throw new AlreadyBuiltException("This method can not be called after 'build()'-function has been called");
}
GraphQLFieldDefinition.Builder ret = newFieldDefinition();
fields.add(ret);
return ret;
}
public GraphQLFieldDefinition.Builder addField(Class<?> clz) {
return addField()
.type(typeForClass(clz))
.name(clz.getSimpleName().toLowerCase());
}
public GraphQLFieldDefinition.Builder addListField(Class<?> clz) {
return addField()
.type(GraphQLList.list(typeForClass(clz)))
.name((clz.getSimpleName() + "s").toLowerCase());
}
/**
* Add a field to graphql schema from JPA metamodel.
* This function will set a name and DataFetcher to the fieldDefinition builder,
* which then can be overriden from the returned builder, if needed
*
* @param field JPA metamodel field to be added to the graphql schema
* @return Field definition builder, where type, name and data fetcher are set according to the {@param field}
*/
public GraphQLFieldDefinition.Builder addField(Attribute<? super T, ?> field) {
GraphQLOutputType type = typeForClass(field.getJavaType());
if (field instanceof PluralAttribute) {
type = GraphQLList.list(typeForClass(((PluralAttribute) field).getBindableJavaType()));
}
return addField()
.type(type)
.name(field.getName().toLowerCase())
.dataFetcher(new PropertyDataFetcher<>(field.getName()));
}
private GraphQLOutputType typeForClass(Class<?> type) {
if (Map.Entry.class.isAssignableFrom(type)) {
return parent.getMapEntryType();
}
if (Boolean.class.isAssignableFrom(type) || boolean.class.isAssignableFrom(type)) {
return GraphQLBoolean;
}
if (Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) {
return GraphQLFloat;
}
if (Byte.class.isAssignableFrom(type) || byte.class.isAssignableFrom(type)) {
return GraphQLByte;
}
if (Character.class.isAssignableFrom(type) || char.class.isAssignableFrom(type)) {
return GraphQLChar;
}
if (Short.class.isAssignableFrom(type) || short.class.isAssignableFrom(type)) {
return GraphQLShort;
}
if (Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) {
return GraphQLInt;
}
if (Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type)) {
return GraphQLLong;
}
if (BigInteger.class.isAssignableFrom(type)) {
return GraphQLBigInteger;
}
if (BigDecimal.class.isAssignableFrom(type)) {
return GraphQLBigDecimal;
}
if (String.class.isAssignableFrom(type)) {
return GraphQLString;
}
if (byte[].class.isAssignableFrom(type) || Byte[].class.isAssignableFrom(type)) {
return GraphQLUtils.GRAPHQL_BYTE_TO_BASE64_TYPE;
}
if (Enum.class.isAssignableFrom(type)) {
return parent.getEnum((Class<Enum>) type);
}
if (Date.class.isAssignableFrom(type)
|| Calendar.class.isAssignableFrom(type)
|| OffsetDateTime.class.isAssignableFrom(type)
|| LocalDateTime.class.isAssignableFrom(type)
|| LocalDate.class.isAssignableFrom(type)) {
return GraphQLUtils.GRAPHQL_DATE_TYPE;
}
return parent.typeFor(type);
}
@Override
public GraphQLObjectType build() {
if (builtObject == null) {
fields.forEach(f -> builder.field(f));
builtObject = builder.build();
}
return builtObject;
}
public GraphQLObjectType.Builder getRawTypeBuilder() {
return builder;
}
public EntityGQLBuilder<T> description(String s) {
builder.description(s);
return this;
}
public GraphQLTypeReference getRef() {
return parent.typeFor(typeName);
}
}
package fi.codecrew.moya.graphql;
import graphql.schema.GraphQLObjectType;
public interface GQLEntityContainer {
GraphQLObjectType build();
}
package fi.codecrew.moya.graphql;
public class GRPDException extends RuntimeException {
public GRPDException(String reason) {
super(reason);
}
}
package fi.codecrew.moya.graphql;
import graphql.schema.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.stream.Collectors;
import static graphql.Scalars.GraphQLString;
import static graphql.schema.GraphQLEnumType.newEnum;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
import static graphql.schema.GraphQLObjectType.newObject;
public class GraphQLBuilder {
private final Map<String, GQLEntityContainer> entities = new HashMap<>();
private final Map<String, GraphQLEnumType> enums = new HashMap<>();
private final Set<String> uncheckedTypes = new HashSet<>();
private static final Logger logger = LoggerFactory.getLogger(GraphQLBuilder.class);
public <T> EntityGQLBuilder<T> createEntity(Class<T> entityClass) {
return createEntity(entityClass.getSimpleName());
}
public <T> EntityGQLBuilder<T> createEntity(String name) {
EntityGQLBuilder<T> ret = new EntityGQLBuilder<>(name, this);
entities.put(name, ret);
return ret;
}
public GraphQLList getMapEntryType() {
if (!entities.containsKey("MapEntry")) {
entities.put("MapEntry", new GQLEntityContainer() {
@Override
public GraphQLObjectType build() {
return type.build();
}
final GraphQLObjectType.Builder type = newObject()
.name("MapEntry")
.field(newFieldDefinition().name("key").type(GraphQLString))
.field(newFieldDefinition().name("value").type(GraphQLString));
}
);
}
return GraphQLList.list(typeFor("MapEntry"));
}
public Set<GraphQLType> getTypes() {
Set<GraphQLType> ret = new HashSet<>(enums.values());
List<GraphQLObjectType> retEnt = entities.values().stream().map(v -> v.build()).collect(Collectors.toList());
logger.warn("Returning entities", retEnt);
ret.addAll(retEnt);
logger.warn("Enums {}, entities {}", enums, entities);
logger.warn("Builder returning types: {}", ret);
return ret;
}
public GraphQLTypeReference typeFor(String typeName) {
logger.warn("Adding typeFor: {}", typeName);
if (!entities.containsKey(typeName) && !enums.containsKey(typeName)) {
logger.warn("Adding unknown type: this might be an error!" + typeName, new RuntimeException().fillInStackTrace());
uncheckedTypes.add(typeName);
}
return GraphQLTypeReference.typeRef(typeName);
}
public GraphQLTypeReference typeFor(Class<?> clz) {
return typeFor(clz.getSimpleName());
}
public <X extends Enum> GraphQLOutputType getEnum(Class<X> type) {
String name = type.getSimpleName();
if (name == null) {
throw new NullPointerException("Trying to get enum with type " + type);
}
if (!enums.containsKey(name)) {
GraphQLEnumType.Builder ret = newEnum().name(name);
for (Enum c : type.getEnumConstants()) {
ret.value(c.name());
}
enums.put(name, ret.build());
}
return typeFor(type);
}
}
package fi.codecrew.moya.graphql;
import graphql.schema.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class GraphQLUtils {
public static final GraphQLScalarType GRAPHQL_BYTE_TO_BASE64_TYPE = new GraphQLScalarType("Base64Data", "Binary data in base64 format", new Coercing<byte[], String>() {
@Override
public String serialize(Object dataFetcherResult) throws CoercingSerializeException {
byte[] data = (byte[]) dataFetcherResult;
if (data == null || data.length == 0) {
return "";
}
return Base64.getEncoder().encodeToString(data);
}
@Override
public byte[] parseValue(Object input) throws CoercingParseValueException {
return Base64.getDecoder().decode(input.toString());
}
@Override
public byte[] parseLiteral(Object input) throws CoercingParseLiteralException {
return Base64.getDecoder().decode(input.toString());
}
});
public static final GraphQLScalarType GRAPHQL_DATE_TYPE = new GraphQLScalarType("Date", "Date in ISO-8601 format: yyyymmddThhmmssZ (for example: 2011-12-03T10:15:30Z')", new Coercing<Object, String>() {
@Override
public String serialize(Object dataFetcherResult) throws CoercingSerializeException {
if (dataFetcherResult == null) {
return null;
}
try {
if (dataFetcherResult instanceof Date) {
return Instant
.ofEpochMilli(((Date) dataFetcherResult).getTime())
.atZone(ZoneId.systemDefault())
.toOffsetDateTime()
.format(DateTimeFormatter.ISO_INSTANT);
} else if (dataFetcherResult instanceof Calendar) {
return Instant
.ofEpochMilli(((Calendar) dataFetcherResult).getTime().getTime())
.atZone(ZoneId.systemDefault())
.toOffsetDateTime()
.format(DateTimeFormatter.ISO_INSTANT);
} else if (dataFetcherResult instanceof OffsetDateTime) {
return ((OffsetDateTime) dataFetcherResult).format(DateTimeFormatter.ISO_INSTANT);
} else if (dataFetcherResult instanceof LocalDateTime) {
return ((LocalDateTime) dataFetcherResult).format(DateTimeFormatter.ISO_INSTANT);
} else if (dataFetcherResult instanceof LocalDate) {
return ((LocalDate) dataFetcherResult).format(DateTimeFormatter.ISO_INSTANT);
}
} catch (Exception e) {
throw new CoercingSerializeException("Error converting detected dateformat: " + dataFetcherResult, e);
}
throw new CoercingSerializeException("Unknonw date type " + dataFetcherResult.getClass());
}
@Override
public Object parseValue(Object input) throws CoercingParseValueException {
throw new UnsupportedOperationException("Not yet implemented... TODO... ");
}
@Override
public Object parseLiteral(Object input) throws CoercingParseLiteralException {
throw new UnsupportedOperationException("Not yet implemented... TODO... ");
}
});
}
package fi.codecrew.moya.graphql.util;
import graphql.execution.ExecutionContext;
import graphql.execution.ExecutionId;
import graphql.execution.ExecutionTypeInfo;
import graphql.language.Field;
import graphql.language.FragmentDefinition;
import graphql.schema.*;
import java.util.List;
import java.util.Map;
public class DataFetchingEnvironmentWrapper<SRCT> implements DataFetchingEnvironment {
private final SRCT source;
private final DataFetchingEnvironment env;
public DataFetchingEnvironmentWrapper(DataFetchingEnvironment environment, SRCT source) {
this.env = environment;
this.source = source;
}
@Override
public SRCT getSource() {
return source;
}
@Override
public Map<String, Object> getArguments() {
return env.getArguments();
}
@Override
public boolean containsArgument(String name) {
return env.containsArgument(name);
}
@Override
public <T> T getArgument(String name) {
return env.getArgument(name);
}
@Override
public <T> T getContext() {
return env.getContext();
}
@Override
public <T> T getRoot() {
return env.getRoot();
}
@Override
public GraphQLFieldDefinition getFieldDefinition() {
return env.getFieldDefinition();
}
@Override
public List<Field> getFields() {
return env.getFields();
}
@Override
public Field getField() {
return env.getField();
}
@Override
public GraphQLOutputType getFieldType() {
return env.getFieldType();
}
@Override
public ExecutionTypeInfo getFieldTypeInfo() {
return env.getFieldTypeInfo();
}
@Override
public GraphQLType getParentType() {
return env.getParentType();
}
@Override
public GraphQLSchema getGraphQLSchema() {
return env.getGraphQLSchema();
}
@Override
public Map<String, FragmentDefinition> getFragmentsByName() {
return env.getFragmentsByName();
}
@Override
public ExecutionId getExecutionId() {
return env.getExecutionId();
}
@Override
public DataFetchingFieldSelectionSet getSelectionSet() {
return env.getSelectionSet();
}
@Override
public ExecutionContext getExecutionContext() {
return env.getExecutionContext();
}
}
package fi.codecrew.moya.graphql.util;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.PropertyDataFetcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.json.JsonObject;
public class JSONPropertyDataFetcher implements DataFetcher<String> {
private static final Logger logger = LoggerFactory.getLogger(JSONPropertyDataFetcher.class);
private final PropertyDataFetcher<JsonObject> fetcher;
private final String[] path;
public JSONPropertyDataFetcher(String field, String... path) {
fetcher = new PropertyDataFetcher<>(field);
this.path = path;
}
@Override
public String get(DataFetchingEnvironment environment) {
JsonObject obj = fetcher.get(environment);
for (int i = 0; i < path.length; ++i) {
if (obj == null || !obj.containsKey(path[i])) {
logger.debug("Json Object null, or key null {}, path {}", obj, path[i] );
return null;
}
if(i + 1 == path.length){
return obj.getString(path[i]);
} else {
obj = obj.getJsonObject(path[i]);
}
}
return null;
}
}
package fi.codecrew.moya.graphql.util;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.PropertyDataFetcher;
public class PropertyFetchWrapper<T, INNER> implements DataFetcher<T> {
private final DataFetcher<INNER> fetcher;
private final DataFetcher<T> innerFetcher;
public PropertyFetchWrapper(String field, DataFetcher<T> innerFetcher) {
this.fetcher = new PropertyDataFetcher<>(field);
this.innerFetcher = innerFetcher;
}
@Override
public T get(DataFetchingEnvironment environment) {
INNER field = fetcher.get(environment);
return innerFetcher.get(new DataFetchingEnvironmentWrapper(environment, field));
}
}
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
/* /*
...@@ -47,7 +47,6 @@ import fi.codecrew.moya.model.LanEventProperty; ...@@ -47,7 +47,6 @@ import fi.codecrew.moya.model.LanEventProperty;
import fi.codecrew.moya.model.LanEventPropertyKey; import fi.codecrew.moya.model.LanEventPropertyKey;
/** /**
*
* @author tuukka * @author tuukka
*/ */
@Named() @Named()
...@@ -85,15 +84,15 @@ public class SessionHandler { ...@@ -85,15 +84,15 @@ public class SessionHandler {
retStr = ret.toLanguageTag(); retStr = ret.toLanguageTag();
} }
if(retStr.trim().equals("")) if (retStr.trim().equals(""))
retStr = "fi_FI"; retStr = "fi_FI";
return retStr; return retStr;
} }
public String getTheme() { public String getTheme() {
if(theme == null) { if (theme == null) {
theme = eventbean.getCurrentEvent().getTheme(); theme = eventbean.getCurrentEvent().getTheme();
} }
if (theme == null || theme.trim().isEmpty()) { if (theme == null || theme.trim().isEmpty()) {
...@@ -102,16 +101,16 @@ public class SessionHandler { ...@@ -102,16 +101,16 @@ public class SessionHandler {
} }
return theme; return theme;
} }
public void setTheme(String theme) { public void setTheme(String theme) {
logger.debug("Setting theme to: "+theme); logger.debug("Setting theme to: " + theme);
} }
public String getFullscreen() { public String getFullscreen() {
template = "fullprimelayout"; template = "fullprimelayout";
return getTemplate(); return getTemplate();
} }
public String getInfoscreen() { public String getInfoscreen() {
template = "infoview"; template = "infoview";
return template; return template;
...@@ -122,12 +121,11 @@ public class SessionHandler { ...@@ -122,12 +121,11 @@ public class SessionHandler {
return template; return template;
} }
public String getTemplateName() public String getTemplateName() {
{
if (template == null) { if (template == null) {
template = eventbean.getPropertyString(LanEventPropertyKey.EVENT_LAYOUT); template = eventbean.getPropertyString(LanEventPropertyKey.EVENT_LAYOUT);
} }
if(template != null){ if (template != null) {
template = template.trim().toLowerCase(); template = template.trim().toLowerCase();
} }
...@@ -137,8 +135,7 @@ public class SessionHandler { ...@@ -137,8 +135,7 @@ public class SessionHandler {
return template; return template;
} }
public String getTemplatePath() public String getTemplatePath() {
{
return "/resources/templates/" + getTemplateName(); return "/resources/templates/" + getTemplateName();
...@@ -150,8 +147,7 @@ public class SessionHandler { ...@@ -150,8 +147,7 @@ public class SessionHandler {
private EnumMap<LanEventPropertyKey, Boolean> boolPropertyCache = new EnumMap<>(LanEventPropertyKey.class); private EnumMap<LanEventPropertyKey, Boolean> boolPropertyCache = new EnumMap<>(LanEventPropertyKey.class);
public boolean isEventBoolProperty(String property) public boolean isEventBoolProperty(String property) {
{
LanEventPropertyKey prop = LanEventPropertyKey.valueOf(property); LanEventPropertyKey prop = LanEventPropertyKey.valueOf(property);
if (!prop.isBoolean()) { if (!prop.isBoolean()) {
throw new RuntimeException("Trying to fetch boolean value for non-boolean property!"); throw new RuntimeException("Trying to fetch boolean value for non-boolean property!");
...@@ -206,18 +202,15 @@ public class SessionHandler { ...@@ -206,18 +202,15 @@ public class SessionHandler {
// return permbean.hasPermission(perm); // return permbean.hasPermission(perm);
// } // }
public String getDateFormat() public String getDateFormat() {
{
return "dd.MM.yyyy"; return "dd.MM.yyyy";
} }
public String getDatetimeFormat() public String getDatetimeFormat() {
{
return "dd.MM.yyyy HH:mm"; return "dd.MM.yyyy HH:mm";
} }
public String getShortDatetimeFormat() public String getShortDatetimeFormat() {
{
return "dd.MM HH:MM:ss"; return "dd.MM HH:MM:ss";
} }
...@@ -247,7 +240,8 @@ public class SessionHandler { ...@@ -247,7 +240,8 @@ public class SessionHandler {
} }
public String flushCache() { public String flushCache() {
return eventbean.flushCache(); eventbean.flushCache();
return "";
} }
...@@ -257,13 +251,10 @@ public class SessionHandler { ...@@ -257,13 +251,10 @@ public class SessionHandler {
private String preurlString; private String preurlString;
public String getRequestPreUrl() public String getRequestPreUrl() {
{ if (preurlString == null) {
if (preurlString == null)
{
Object ext = FacesContext.getCurrentInstance().getExternalContext().getRequest(); Object ext = FacesContext.getCurrentInstance().getExternalContext().getRequest();
if (ext instanceof HttpServletRequest) if (ext instanceof HttpServletRequest) {
{
StringBuffer url = ((HttpServletRequest) ext).getRequestURL(); StringBuffer url = ((HttpServletRequest) ext).getRequestURL();
preurlString = url.substring(0, url.indexOf("/", 8)); preurlString = url.substring(0, url.indexOf("/", 8));
......
...@@ -22,7 +22,7 @@ public class PojoFactoryV2 implements Serializable { ...@@ -22,7 +22,7 @@ public class PojoFactoryV2 implements Serializable {
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public UserPojo createUserPojo(EventUser eventUser) { public static UserPojo createUserPojo(EventUser eventUser) {
User user = eventUser.getUser(); User user = eventUser.getUser();
UserPojo pojo = new UserPojo(); UserPojo pojo = new UserPojo();
pojo.eventuserId = eventUser.getId(); pojo.eventuserId = eventUser.getId();
......
...@@ -33,7 +33,7 @@ import fi.codecrew.moya.model.CardTemplate; ...@@ -33,7 +33,7 @@ import fi.codecrew.moya.model.CardTemplate;
/** /**
* Servlet implementation class UploadServlet * Servlet implementation class UploadServlet
*/ */
@WebServlet("/CardTemplate") @WebServlet(value="/CardTemplate")
public class CardTemplateServlet extends GenericImageServlet { public class CardTemplateServlet extends GenericImageServlet {
/** /**
......
package fi.codecrew.moya.servlet;
import fi.codecrew.moya.beans.VotingBeanLocal;
import fi.codecrew.moya.model.*;
import fi.codecrew.moya.utilities.SystemProperty;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@WebServlet(value = "/EntryFile/*")
public class CompoEntryFileServlet extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(CompoEntryFileServlet.class);
/**
* @see HttpServlet#HttpServlet()
*/
public CompoEntryFileServlet() {
super();
logger.warn("Initializing StreamingUploadServlet");
}
@EJB
private VotingBeanLocal votebean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int fileId = Integer.parseUnsignedInt(req.getPathInfo().substring(1));
CompoEntryFile entry = votebean.findEntryFile(fileId);
if (entry == null) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
resp.getWriter().write("Entity not found");
return;
}
File file = new File(new File(SystemProperty.MOYA_COMPOFILE_DIR.getValueOrDefault()), entry.getFilepath());
resp.setContentType(entry.getMimeType());
resp.setHeader("Content-Disposition", "filename=\"" + entry.getFileName() + "\"");
resp.setContentLength((int) file.length());
FileInputStream inStream = new FileInputStream(file);
ServletOutputStream oStream = resp.getOutputStream();
final byte[] buff = new byte[8192];
while (true) {
int len = inStream.read(buff);
if (len < 1) {
break;
}
oStream.write(buff, 0, len);
}
oStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
File dir = new File(SystemProperty.MOYA_COMPOFILE_DIR.getValueOrDefault());
if (!dir.isDirectory()) {
dir.mkdirs();
}
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
if (!isMultipart) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Expected multipart upload");
return;
}
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iter = upload.getItemIterator(req);
final byte[] buff = new byte[8192];
File tmpFile = File.createTempFile("moya-file", "tmp", dir);
CompoEntryFile entryfile = new CompoEntryFile();
Integer entryId = 0;
Integer typeId = 0;
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
final String data = Streams.asString(stream);
logger.warn("Streaming upload form field " + name + " with value " + data + " detected.");
switch (name) {
case "entryId": {
entryId = Integer.parseInt(data);
break;
}
case "typeId": {
typeId = Integer.parseInt(data);
break;
}
}
} else {
logger.warn("File field " + name + " with file name " + item.getName() + " detected." + item.getContentType());
MessageDigest algo = MessageDigest.getInstance("SHA");
FileOutputStream ostream = new FileOutputStream(tmpFile);
while (true) {
int len = stream.read(buff);
if (len < 1) {
break;
}
ostream.write(buff, 0, len);
algo.update(buff, 0, len);
}
String shasum = new String(Hex.encodeHex(algo.digest())).toLowerCase();
logger.warn("File shasum " + shasum);
ostream.close();
entryfile.setFileName(item.getName());
entryfile.setMimeType(item.getContentType());
entryfile.setHash(shasum);
}
stream.close();
}
CompoEntryFileType ft = votebean.findEntryFileType(entryId, typeId);
String ftPath = mkEntryFiletypePath(ft);
File filetypepath = new File(dir, ftPath);
if (!filetypepath.isDirectory()) {
filetypepath.mkdirs();
}
String filePath = ftPath + mkPath(entryfile.getUploaded().getTime() + "_" + entryfile.getFileName()) + ".dat";
logger.warn("Target file: {}, ftpath {}", filePath, ftPath);
entryfile.setFilepath(filePath);
if (!tmpFile.renameTo(new File(dir, filePath))) {
throw new RuntimeException("Error moving file to " + filePath);
}
entryfile.setFiletype(ft);
votebean.create(entryfile);
resp.setStatus(HttpServletResponse.SC_SEE_OTHER);
resp.setHeader("Location", "/MoyaWeb/voting/submitEntry.jsf?entryId=" + entryId);
} catch (FileUploadException e) {
logger.warn("Error uploading streaming file", e);
} catch (NoSuchAlgorithmException e) {
logger.warn("Error calculating checksum", e);
}
}
String asString(InputStream stream) throws IOException {
final byte[] buff = new byte[100];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (true) {
int len = stream.read(buff);
if (len < 1) {
break;
}
baos.write(buff, 0, len);
}
return baos.toString();
}
public static void main(String[] asd) {
logger.warn("asda {}", mkPath("Foo", "[]{}äöherp", "1239KKKKK"));
}
public static String mkPath(Object... paths) {
StringBuilder ret = new StringBuilder();
for (Object p : paths) {
ret.append("/");
ret.append(p.toString().toLowerCase().replaceAll("[^a-z0-9]", "_"));
}
return ret.toString().replaceAll("_+", "_");
}
public static String mkEntryFiletypePath(CompoEntryFileType type) {
final CompoEntry entry = type.getEntry();
;
final Compo compo = entry.getCompo();
final LanEvent event = compo.getEvent();
return mkPath(
event.getId() + "_ " + event.getName(),
compo.getId() + "_" + compo.getName(),
entry.getId() + "_" + entry.getTitle(),
type.getId() + "_" + type.getType().getName()
);
}
}
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
package fi.codecrew.moya.servlet; package fi.codecrew.moya.servlet;
...@@ -83,7 +83,6 @@ public class UploadServlet extends HttpServlet { ...@@ -83,7 +83,6 @@ public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// boolean isMultipart = ServletFileUpload.isMultipartContent(request); // boolean isMultipart = ServletFileUpload.isMultipartContent(request);
FileItemFactory factory = new DiskFileItemFactory(); FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request // Parse the request
CharSequence retmsg = "Tiedosto tallennettu onnistuneesti."; CharSequence retmsg = "Tiedosto tallennettu onnistuneesti.";
...@@ -106,6 +105,9 @@ public class UploadServlet extends HttpServlet { ...@@ -106,6 +105,9 @@ public class UploadServlet extends HttpServlet {
destId = null; destId = null;
} }
} }
ServletFileUpload upload = new ServletFileUpload(factory);
for (Object ti : upload.parseRequest(request)) { for (Object ti : upload.parseRequest(request)) {
if (ti instanceof FileItem) { if (ti instanceof FileItem) {
......
package fi.codecrew.moya.web.api;
import fi.codecrew.moya.beans.ApiApplicationBeanLocal;
import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.model.ApiApplication;
import fi.codecrew.moya.model.ApiApplicationInstance;
import fi.codecrew.moya.utilities.PasswordFunctions;
import fi.codecrew.moya.web.cdiview.GenericCDIView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.EJB;
import javax.enterprise.context.ConversationScoped;
import javax.faces.model.ListDataModel;
import javax.inject.Named;
import java.util.List;
@Named
@ConversationScoped
public class ApiAppEditView extends GenericCDIView {
private static final long serialVersionUID = -5137452386861332063L;
@EJB
private ApiApplicationBeanLocal apibean;
@EJB
private PermissionBeanLocal permbean;
private ApiApplication apiApp;
private Integer id;
private ApiApplicationInstance selectedInstance;
private ListDataModel<ApiApplicationInstance> apiInstances;
public void initEdit() {
if (super.requirePermissions(permbean.isLoggedIn()) && apiApp == null) {
super.beginConversation();
apiApp = apibean.findApplication(id);
apiInstances = new ListDataModel<>(apibean.findInstances(apiApp));
}
}
public void initCreateInstance() {
selectedInstance = apibean.createApplicationInstance(apiApp);
}
public void selectInstance(){
selectedInstance = apiInstances.getRowData();
}
public void saveInstance() {
apibean.saveApiInstance(selectedInstance);
}
public String save() {
apiApp = apibean.saveApiApplication(apiApp);
return null;
}
public ApiApplication getApiApp() {
return apiApp;
}
public void setApiApp(ApiApplication apiApp) {
this.apiApp = apiApp;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public ApiApplicationInstance getSelectedInstance() {
return selectedInstance;
}
public void setSelectedInstance(ApiApplicationInstance selectedInstance) {
this.selectedInstance = selectedInstance;
}
public ListDataModel<ApiApplicationInstance> getApiInstances() {
return apiInstances;
}
public void setApiInstances(ListDataModel<ApiApplicationInstance> apiInstances) {
this.apiInstances = apiInstances;
}
}
...@@ -39,17 +39,24 @@ public class ApplicationApiView extends GenericCDIView { ...@@ -39,17 +39,24 @@ public class ApplicationApiView extends GenericCDIView {
private static final Logger logger = LoggerFactory.getLogger(ApplicationApiView.class); private static final Logger logger = LoggerFactory.getLogger(ApplicationApiView.class);
public void initApplicationListView() { public void initApplicationListView() {
if (super.requirePermissions(permbean.isLoggedIn()) && applist == null) { if (super.requirePermissions(permbean.isLoggedIn()) && applist == null) {
EventUser curruser = permbean.getCurrentUser(); applist = apibean.findMyApplications();
if (permbean.hasPermission(SpecialPermission.SUPERADMIN)) { }
applist = apibean.findAllApplications(); }
} else {
applist = apibean.findMyApplications(); public void initSuperApplicationListView() {
} if (super.requirePermissions(permbean.hasPermission(SpecialPermission.SUPERADMIN)) && applist == null) {
applist = apibean.findAllApplications();
} }
} }
public String createApp() {
apibean.createApiApplication(newApplication);
return "/api/edit?faces-redirect=true&id=" + newApplication.getId();
}
public List<ApiApplication> getApplist() { public List<ApiApplication> getApplist() {
return applist; return applist;
} }
......
...@@ -98,7 +98,7 @@ public class UserAllergyView extends GenericCDIView { ...@@ -98,7 +98,7 @@ public class UserAllergyView extends GenericCDIView {
this.freetext = freetext; this.freetext = freetext;
} }
public void saveAllergies() { public void saveAllergies() {
if(freetext != null && !freetext.isEmpty()) { if(freetext != null) {
EventUser usr = userview.getSelectedUser(); EventUser usr = userview.getSelectedUser();
usr.getUser().setMetaStringValue(ALLERGIES_METAKEY, freetext); usr.getUser().setMetaStringValue(ALLERGIES_METAKEY, freetext);
userview.saveUser(); userview.saveUser();
......
/*
* Copyright Codecrew Ry
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*/
package fi.codecrew.moya.web.cdiview.user;
import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.beans.UserPropertyBeanLocal;
import fi.codecrew.moya.model.*;
import fi.codecrew.moya.utilities.jsf.MessageHelper;
import fi.codecrew.moya.web.cdiview.GenericCDIView;
import org.primefaces.event.RowEditEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.EJB;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;
import java.util.stream.Collectors;
@Named()
@ConversationScoped
public class UserEventPropertyView extends GenericCDIView {
private static final Logger logger = LoggerFactory.getLogger(UserEventPropertyView.class);
@Inject
private UserView userview;
@EJB
private UserBeanLocal userbean;
@EJB
private UserPropertyBeanLocal propBean;
private List<UsersEventUserproperty> properties;
private UsersEventUserproperty selectedProperty;
public void saveProperty() {
logger.warn("Selected property {}, value: {}", selectedProperty, selectedProperty != null ? selectedProperty.getTextvalue() : "NULL");
}
public List<UsersEventUserproperty> getProperties() {
if (properties == null) {
super.beginConversation();
EventUser selectedUser = userview.getSelectedUser();
List<UsersEventUserproperty> userprops = propBean.getUserPropertiesForUser(userview.getSelectedUser());
properties = propBean.getPropertiesForUser(userview.getSelectedUser())
.stream()
.map(prop -> userprops.stream()
.filter(usrProp -> usrProp.getProperty().equals(prop))
.findFirst()
.orElse(new UsersEventUserproperty(prop, selectedUser)))
.collect(Collectors.toList());
}
logger.warn("UserEventProperties: ", properties);
return properties;
}
public void onRowEdit(RowEditEvent event) {
final UsersEventUserproperty oldObj = (UsersEventUserproperty) event.getObject();
int objPoint = properties.indexOf(oldObj);
UsersEventUserproperty newObj = propBean.saveUserproperty(oldObj);
properties.set(objPoint, newObj);
FacesMessage msg = new FacesMessage("Property saved");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edit Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
package fi.codecrew.moya.web.cdiview.user; package fi.codecrew.moya.web.cdiview.user;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.HashMap; import java.util.*;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.enterprise.context.Conversation; import javax.enterprise.context.Conversation;
...@@ -78,7 +76,7 @@ import fi.codecrew.moya.web.helper.LayoutView; ...@@ -78,7 +76,7 @@ import fi.codecrew.moya.web.helper.LayoutView;
public class UserView extends GenericCDIView { public class UserView extends GenericCDIView {
/** /**
* *
*/ */
private static final Logger logger = LoggerFactory.getLogger(UserView.class); private static final Logger logger = LoggerFactory.getLogger(UserView.class);
private static final long serialVersionUID = 7724348195373468017L; private static final long serialVersionUID = 7724348195373468017L;
...@@ -90,21 +88,21 @@ public class UserView extends GenericCDIView { ...@@ -90,21 +88,21 @@ public class UserView extends GenericCDIView {
public int tabIdx(String name) { public int tabIdx(String name) {
switch (name) { switch (name) {
case "edit": case "edit":
return 0; return 0;
case "shop": case "shop":
return 1; return 1;
case "accountevents": case "accountevents":
return 2; return 2;
case "groups": case "groups":
return 3; return 3;
case "picture": case "picture":
return 4; return 4;
case "foodwave": case "foodwave":
return 5; return 5;
default: default:
} }
return 0; return 0;
} }
...@@ -174,7 +172,7 @@ public class UserView extends GenericCDIView { ...@@ -174,7 +172,7 @@ public class UserView extends GenericCDIView {
/** /**
* This is the user that is currently logged in. * This is the user that is currently logged in.
* *
* @return * @return
*/ */
@Produces @Produces
...@@ -189,7 +187,7 @@ public class UserView extends GenericCDIView { ...@@ -189,7 +187,7 @@ public class UserView extends GenericCDIView {
FacesContext.getCurrentInstance().addMessage(null, msg); FacesContext.getCurrentInstance().addMessage(null, msg);
UploadedFile f = event.getFile(); UploadedFile f = event.getFile();
if (f != null) if (f != null)
logger.info("Received file {}, {}, {}", new Object[] { f.getContentType(), f.getFileName(), f.getSize() }); logger.info("Received file {}, {}, {}", new Object[]{f.getContentType(), f.getFileName(), f.getSize()});
} }
...@@ -207,7 +205,7 @@ public class UserView extends GenericCDIView { ...@@ -207,7 +205,7 @@ public class UserView extends GenericCDIView {
/** /**
* This is the user we are currently editing, if that is not found we use * This is the user we are currently editing, if that is not found we use
* current user * current user
* *
* @return * @return
*/ */
@Produces @Produces
...@@ -231,6 +229,11 @@ public class UserView extends GenericCDIView { ...@@ -231,6 +229,11 @@ public class UserView extends GenericCDIView {
return null; return null;
} }
public ArrayList<Map.Entry<Role, List<String>>> getAllUsersRoles(){
return new ArrayList<>(userbean.findUsersRolesWithReason(user).entrySet());
}
public List<Role> getUserSelectableRoles() { public List<Role> getUserSelectableRoles() {
if (userSelectableRoles == null && user != null) { if (userSelectableRoles == null && user != null) {
userSelectableRoles = rolebean.getRoles(getSelectedUser()); userSelectableRoles = rolebean.getRoles(getSelectedUser());
...@@ -260,11 +263,11 @@ public class UserView extends GenericCDIView { ...@@ -260,11 +263,11 @@ public class UserView extends GenericCDIView {
logger.info("Cropped image {}x{}", croppedImage.getLeft(), croppedImage.getTop()); logger.info("Cropped image {}x{}", croppedImage.getLeft(), croppedImage.getTop());
logger.info("Cropped data bytesize {}, type {}", croppedImage.getBytes().length, logger.info("Cropped data bytesize {}, type {}", croppedImage.getBytes().length,
croppedImage.getOriginalFilename()); croppedImage.getOriginalFilename());
try { try {
UserImage newImage = userbean.saveCroppedImage(user.getUser().getCurrentImage(), croppedImage.getLeft(), UserImage newImage = userbean.saveCroppedImage(user.getUser().getCurrentImage(), croppedImage.getLeft(),
croppedImage.getTop(), croppedImage.getWidth(), croppedImage.getHeight()); croppedImage.getTop(), croppedImage.getWidth(), croppedImage.getHeight());
user = userbean.getEventUser(newImage.getUser(), false); user = userbean.getEventUser(newImage.getUser(), false);
} catch (IOException e) { } catch (IOException e) {
...@@ -279,7 +282,7 @@ public class UserView extends GenericCDIView { ...@@ -279,7 +282,7 @@ public class UserView extends GenericCDIView {
mpr = cardPrintBean.getUserCardAsPrintablePdf(getSelectedUser().getId()); mpr = cardPrintBean.getUserCardAsPrintablePdf(getSelectedUser().getId());
ByteArrayInputStream pdfstream = new ByteArrayInputStream(mpr.getPdf()); ByteArrayInputStream pdfstream = new ByteArrayInputStream(mpr.getPdf());
setStreamedFile(new DefaultStreamedContent(pdfstream, "application/pdf", setStreamedFile(new DefaultStreamedContent(pdfstream, "application/pdf",
"user_" + getSelectedUser().getId() + "_card.pdf")); "user_" + getSelectedUser().getId() + "_card.pdf"));
logger.info("user_" + getSelectedUser().getId() + "_card.pdf"); logger.info("user_" + getSelectedUser().getId() + "_card.pdf");
} catch (Exception e) { } catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage())); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
...@@ -311,7 +314,7 @@ public class UserView extends GenericCDIView { ...@@ -311,7 +314,7 @@ public class UserView extends GenericCDIView {
} else { } else {
UserImage userimage = userbean.uploadImage(user, getImage().getContentType(), getImage().getInputstream(), UserImage userimage = userbean.uploadImage(user, getImage().getContentType(), getImage().getInputstream(),
getImage().getFileName(), ""); getImage().getFileName(), "");
user = userbean.getEventUser(userimage.getUser(), false); user = userbean.getEventUser(userimage.getUser(), false);
super.addFaceMessage("user.imageUploaded"); super.addFaceMessage("user.imageUploaded");
} }
...@@ -409,7 +412,7 @@ public class UserView extends GenericCDIView { ...@@ -409,7 +412,7 @@ public class UserView extends GenericCDIView {
/** /**
* attach barcode or rfid to card * attach barcode or rfid to card
* *
* @return * @return
*/ */
public String attachCodeToCard() { public String attachCodeToCard() {
...@@ -497,7 +500,7 @@ public class UserView extends GenericCDIView { ...@@ -497,7 +500,7 @@ public class UserView extends GenericCDIView {
/** /**
* This is user what is currently on "user" -variable, you should almost * This is user what is currently on "user" -variable, you should almost
* newer use this. Use getCurrentUser() -instead. * newer use this. Use getCurrentUser() -instead.
* *
* @return * @return
*/ */
public EventUser getUser() { public EventUser getUser() {
...@@ -635,9 +638,14 @@ public class UserView extends GenericCDIView { ...@@ -635,9 +638,14 @@ public class UserView extends GenericCDIView {
return shirtEnabled; return shirtEnabled;
} }
public boolean isMetaAvailable(){
JsonObject meta = getSelectedUser().getUser().getMeta();
return meta != null && !meta.isEmpty();
}
/** /**
* Get metadata from the User (not EventUser). The data is shown in ui. * Get metadata from the User (not EventUser). The data is shown in ui.
* *
* @return * @return
*/ */
public String getMeta() { public String getMeta() {
...@@ -646,19 +654,17 @@ public class UserView extends GenericCDIView { ...@@ -646,19 +654,17 @@ public class UserView extends GenericCDIView {
User user = eventUser.getUser(); User user = eventUser.getUser();
if (user != null) { if (user != null) {
JsonObject meta = user.getMeta(); JsonObject meta = user.getMeta();
if (meta != null) { if (meta != null && !meta.isEmpty()) {
if (meta.keySet().size() > 0) { return meta.toString();
return meta.toString();
}
} }
} }
} }
return ""; return "";
} }
public String getPrettyMeta(){ public String getPrettyMeta() {
JsonObject meta = getSelectedUser().getUser().getMeta(); JsonObject meta = getSelectedUser().getUser().getMeta();
if(meta == null){ if (meta == null) {
return ""; return "";
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!