package de.romankreisel.faktotum.handlers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.servlet.http.Part;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.DualListModel;
import org.primefaces.model.StreamedContent;
import de.romankreisel.faktotum.beans.BundesbruderBean;
import de.romankreisel.faktotum.beans.SettingBean;
import de.romankreisel.faktotum.dao.BundesbruderDao;
import de.romankreisel.faktotum.datamodel.BundesbruderEntity;
import de.romankreisel.faktotum.datamodel.BundesbruderEntity.Permission;
import de.romankreisel.faktotum.exceptions.InvalidPasswordException;
@ManagedBean
@SessionScoped
public class BundesbruderHandler extends FaktotumHandler {
/**
*
*/
private static final long serialVersionUID = 1873769579853254380L;
@EJB
private BundesbruderDao bundesbruderDao;
private BundesbruderEntity currentBundesbruder = new BundesbruderEntity();
@ManagedProperty(value = "#{authenticationHandler}")
private AuthenticationHandler authenticationHandler;
@EJB
private BundesbruderBean bundesbruderBean;
@EJB
private SettingBean settingBean;
private String password1;
private String password2;
private String searchString;
private List<BundesbruderEntity> searchResult = new ArrayList<>();
private DualListModel<String> permissions = this.createPermissionList();
private Part profilePicture;
public String createFirstBundesbruder() {
this.getCurrentBundesbruder().getPermissions().add(Permission.SYSTEM_ADMINISTRATION);
this.getPermissions().getTarget().add(Permission.SYSTEM_ADMINISTRATION.toString());
return this.save();
}
/**
* @return
*/
private DualListModel<String> createPermissionList() {
List<String> source = new ArrayList<>(Permission.values().length);
for (Permission permission : Permission.values()) {
// already set permissions must be removed or they will be shown
// twice!
if (!this.getCurrentBundesbruder().getPermissions().contains(permission)) {
source.add(permission.name());
}
}
ArrayList<String> target = new ArrayList<>(this.getCurrentBundesbruder().getPermissions().size());
for (Permission permission : this.getCurrentBundesbruder().getPermissions()) {
target.add(permission.name());
}
return new DualListModel<>(source, target);
}
public String editBundesbruder(BundesbruderEntity bundesbruder) {
this.setPassword1(null);
this.setPassword2(null);
this.setPermissions(this.createPermissionList());
this.setCurrentBundesbruder(bundesbruder);
return "edit";
}
public String findBundesbruderBySearchString(String searchString) {
this.getLogger().finer("Searching for BB with search string " + searchString);
FacesContext context = FacesContext.getCurrentInstance();
Boolean searchAlsoInAlias = this.settingBean.getBooleanSettingValue(SettingBean.SETTING_BOOLEAN_FRATERNITY_USES_ALIASES);
this.searchResult = this.bundesbruderDao.findBySearchString(searchString, searchAlsoInAlias);
this.getLogger().finer((this.searchResult != null ? this.searchResult.size() : "null") + " hit(s) found for search string " + searchString);
if (this.searchResult != null && !this.searchResult.isEmpty()) {
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "BB gefunden!", this.searchResult.size() + " Treffer"));
return "success";
} else {
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Keine Suchtreffer!", "Zu dieser Suchanfrage wurden keine Treffer gefunden!"));
return "empty";
}
}
public String getBundesbruderName(BundesbruderEntity bundesbruder) {
Boolean fraternityUsesAliases = this.settingBean.getBooleanSettingValue(SettingBean.SETTING_BOOLEAN_FRATERNITY_USES_ALIASES);
String firstName = bundesbruder.getFirstName();
String lastName = bundesbruder.getLastName();
StringBuffer returnValue = new StringBuffer();
if (StringUtils.isNotBlank(firstName)) {
returnValue.append(firstName.trim());
}
if (StringUtils.isNotBlank(firstName) && StringUtils.isNotBlank(lastName)) {
returnValue.append(" ");
}
if (StringUtils.isNotBlank(lastName)) {
returnValue.append(lastName.trim());
}
if (fraternityUsesAliases) {
String alias = bundesbruder.getAlias();
if (returnValue.length() > 0 && StringUtils.isNotBlank(alias)) {
returnValue.append(" ");
}
if (StringUtils.isNotBlank(alias)) {
returnValue.append("v. ");
returnValue.append(alias);
}
}
return returnValue.toString();
}
public Long getCount() {
return this.bundesbruderDao.getCount(BundesbruderEntity.class);
}
public BundesbruderEntity getCurrentBundesbruder() {
return this.currentBundesbruder;
}
/**
* @return the password1
*/
public String getPassword1() {
return this.password1;
}
/**
* @return the password2
*/
public String getPassword2() {
return this.password2;
}
/**
* @return the permissions
*/
public DualListModel<String> getPermissions() {
return this.permissions;
}
public StreamedContent getProfileOriginalPictureFromBundesbruder(BundesbruderEntity bundesbruder) {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
// So, we're rendering the view. Return a stub StreamedContent so
// that it will generate right URL.
return new DefaultStreamedContent();
} else {
return new DefaultStreamedContent(new ByteArrayInputStream(ArrayUtils.toPrimitive(bundesbruder.getPictureOriginal())));
}
}
/**
* @return the profilePicture
*/
public Part getProfilePicture() {
return this.profilePicture;
}
public StreamedContent getProfilePictureFromBundesbruder(BundesbruderEntity bundesbruder) {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
// So, we're rendering the view. Return a stub StreamedContent so
// that it will generate right URL.
return new DefaultStreamedContent();
} else {
return new DefaultStreamedContent(new ByteArrayInputStream(ArrayUtils.toPrimitive(bundesbruder.getPicture())));
}
}
public StreamedContent getProfileThumbnailPictureFromBundesbruder(BundesbruderEntity bundesbruder) {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
// So, we're rendering the view. Return a stub StreamedContent so
// that it will generate right URL.
return new DefaultStreamedContent();
} else {
// TODO: get default image, if bb has no image set
return new DefaultStreamedContent(new ByteArrayInputStream(ArrayUtils.toPrimitive(bundesbruder.getPictureThumbnail())));
}
}
/**
* @return the searchResult
*/
public List<BundesbruderEntity> getSearchResult() {
return this.searchResult;
}
/**
* @return the searchString
*/
public String getSearchString() {
return this.searchString;
}
public boolean isMembershipAdministrator(Boolean admin) {
return this.getCurrentBundesbruder().getPermissions().contains(Permission.MEMBERSHIP_ADMINISTRATION);
}
public boolean isMembershipAdministratorOnlyActiveStudents(Boolean admin) {
return this.getCurrentBundesbruder().getPermissions().contains(Permission.STUDENT_MEMBERSHIP_ADMINISTRATION);
}
public boolean isSystemAdministrator(Boolean admin) {
return this.getCurrentBundesbruder().getPermissions().contains(Permission.SYSTEM_ADMINISTRATION);
}
public String rotateProfilePictureClockwise() {
try {
this.bundesbruderBean.rotateProfilePictureClockwise(this.getCurrentBundesbruder(), 90.0);
} catch (IOException e) {
this.getLogger().log(Level.WARNING, "Error rotating image", e);
return "error";
}
return "";
}
public String rotateProfilePictureCounterClockwise() {
try {
this.bundesbruderBean.rotateProfilePictureClockwise(this.getCurrentBundesbruder(), -90.0);
} catch (IOException e) {
this.getLogger().log(Level.WARNING, "Error rotating image", e);
return "error";
}
return "";
}
public String save() {
FacesContext context = FacesContext.getCurrentInstance();
this.getCurrentBundesbruder().getPermissions().clear();
for (String permissionString : this.getPermissions().getTarget()) {
Permission permission = Permission.valueOf(permissionString);
this.getCurrentBundesbruder().getPermissions().add(permission);
}
if (!StringUtils.isEmpty(this.getPassword1()) || StringUtils.isEmpty(this.getPassword2())) {
if (this.getPassword1() != null && this.getPassword2() != null) {
if (!this.getPassword1().equals(this.getPassword2())) {
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Das Kennwort wurde nicht geändert!",
"Die eingegebenen Passwörter sind nicht identisch!"));
this.setPassword1(null);
this.setPassword2(null);
} else {
try {
this.bundesbruderBean.encryptAndSetPassword(this.getCurrentBundesbruder(), this.getPassword1());
} catch (InvalidPasswordException e) {
this.getLogger().log(Level.WARNING, "Invalid Password tried", e);
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ungültiges Kennwort!",
"Die eingegebenen Passwörter sind nicht identisch!"));
this.setPassword1(null);
this.setPassword2(null);
return "error";
}
}
} else if (this.getPassword1() == null && this.getPassword2() == null) {
// no password change, everything is fine
} else {
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ungültiges Kennwort!", "Passwort muss wiederholt eingegeben werden!"));
this.setPassword1(null);
this.setPassword2(null);
return "error";
}
}
this.setCurrentBundesbruder(this.bundesbruderDao.merge(this.getCurrentBundesbruder()));
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Änderungen wurden gespeichert", ""));
this.getLogger().info("BB " + this.getBundesbruderName(this.getCurrentBundesbruder()) + " saved");
return "";
}
/**
* @param authenticationHandler
* the authenticationHandler to set
*/
public void setAuthenticationHandler(AuthenticationHandler authenticationHandler) {
this.authenticationHandler = authenticationHandler;
}
public void setCurrentBundesbruder(BundesbruderEntity currentBundesbruder) {
this.currentBundesbruder = currentBundesbruder;
}
public void setMembershipAdministrator(Boolean admin) {
if (!this.getCurrentBundesbruder().getPermissions().contains(Permission.MEMBERSHIP_ADMINISTRATION)) {
this.getCurrentBundesbruder().getPermissions().add(Permission.MEMBERSHIP_ADMINISTRATION);
}
}
public void setMembershipAdministratorOnlyActiveStudents(Boolean admin) {
if (!this.getCurrentBundesbruder().getPermissions().contains(Permission.STUDENT_MEMBERSHIP_ADMINISTRATION)) {
this.getCurrentBundesbruder().getPermissions().add(Permission.STUDENT_MEMBERSHIP_ADMINISTRATION);
}
}
/**
* @param password1
* the password1 to set
*/
public void setPassword1(String password1) {
this.password1 = password1;
}
/**
* @param password2
* the password2 to set
*/
public void setPassword2(String password2) {
this.password2 = password2;
}
/**
* @param permissions
* the permissions to set
*/
public void setPermissions(DualListModel<String> permissions) {
this.permissions = permissions;
}
/**
* @param profilePicture
* the profilePicture to set
*/
public void setProfilePicture(Part profilePicture) {
this.profilePicture = profilePicture;
}
/**
* @param searchResult
* the searchResult to set
*/
public void setSearchResult(List<BundesbruderEntity> searchResult) {
this.searchResult = searchResult;
}
/**
* @param searchString
* the searchString to set
*/
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public void setSystemAdministrator(Boolean admin) {
if (!this.getCurrentBundesbruder().getPermissions().contains(Permission.SYSTEM_ADMINISTRATION)) {
this.getCurrentBundesbruder().getPermissions().add(Permission.SYSTEM_ADMINISTRATION);
}
}
/**
* Triggered when uploading a profile picture
*/
public String uploadProfilePicture() {
FacesContext context = FacesContext.getCurrentInstance();
if (this.getProfilePicture() == null) {
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Fehlgeschlagen", "Keine Datei hochgeladen"));
return "";
}
InputStream is = null;
try {
is = this.getProfilePicture().getInputStream();
byte[] buffer = new byte[1024];
ArrayList<Byte> pictureByteArray = new ArrayList<>();
int length;
while ((length = is.read(buffer)) >= 0) {
pictureByteArray.ensureCapacity(pictureByteArray.size() + length);
for (int i = 0; i < length; ++i) {
pictureByteArray.add(buffer[i]);
}
}
Byte[] originalPicture = pictureByteArray.toArray(new Byte[pictureByteArray.size()]);
this.bundesbruderBean.setProfilePicture(this.getCurrentBundesbruder(), originalPicture);
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Erfolg", "Datei erfolgreich hochgeladen!"));
} catch (IOException e) {
this.getLogger().log(Level.WARNING, "Error reading profile picture", e);
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Fehlgeschlagen", "Fehler beim hochladen des Profilbilds!"));
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
this.getLogger().log(Level.WARNING, "Error closing profile picture part", e);
}
}
}
return "";
}
}