blob: 8d4ea47d029ec7c044c91bd6533b1fedc41df263 [file] [log] [blame]
/**
*
* Copyright (c) 2011, 2016 - Loetz GmbH&Co.KG (69115 Heidelberg, Germany)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Christophe Loetz (Loetz GmbH&Co.KG) - initial implementation
*/
package org.eclipse.osbp.user;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.eclipse.e4.core.di.extensions.EventUtils;
import org.eclipse.e4.core.services.translation.TranslationService;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.osbp.ui.api.user.IUser;
import org.eclipse.osbp.ui.api.user.filter.FilterMap;
import org.eclipse.osbp.ui.api.useraccess.IUserAccessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.vaadin.server.VaadinSession;
/**
* The Class User represents the subject currently signed in and carries his
* data. User can be injected. It conforms the vaaclipse AuthenticationProvider
* mechanism.
*/
public class User extends Hashtable<String, Object> implements IUser { // NOSONAR
/** The application. */
private transient MApplication application;
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The id. */
private String id;
/** The user name. */
private String userName;
/** The position. */
private String position;
/** The perspective. */
private String perspective;
/** The extra password. */
private String extraPassword;
/** The superuser. */
private boolean superuser;
/** The email. */
private String email;
/** The roles. */
private Collection<String> roles;
/** The locale. */
private Locale locale;
/** The theme. */
private String theme;
/** The print service. */
private String printService;
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(User.class);
/** The listeners. */
private transient List<UserLocaleListener> listeners;
/** The profile image id. */
private String profileImageId;
/** The persisted properties of the user **/
private transient Map<String, Object> properties;
/** The flag to determine if the properties map is changed but not already persisted. **/
private boolean dirtyPropertiesMap;
/** Internal class instance as wrapper for the properties. **/
private transient IColumnUtil columnUtil;
private transient FilterMap userFilter;
private transient DocumentBuilderFactory dbf;
private transient DocumentBuilder docBuilder;
private transient Document filterDocument;
private transient TransformerFactory transformerFactory;
private transient Transformer transformer;
private String filterFilePath;
private boolean saveSettingsAsFile = false;
/**
* Instantiates a new user.
*
* @param userName
* the user name
*/
/**
* @param userName
* the user name
*/
public User(String userName) {
super();
this.userName = userName;
if (UserBinder.getUserAccessService() != null) {
profileImageId = UserBinder.getUserAccessService().getProfileimageId();
position = UserBinder.getUserAccessService().getPositionName();
perspective = UserBinder.getUserAccessService().getPerspective();
extraPassword = UserBinder.getUserAccessService().getExtraPassword();
superuser = UserBinder.getUserAccessService().isSuperuser();
email = UserBinder.getUserAccessService().getEmail();
roles = UserBinder.getUserAccessService().getRoles();
id = UserBinder.getUserAccessService().getId();
theme = UserBinder.getUserAccessService().getTheme();
printService = UserBinder.getUserAccessService().getPrintService();
properties = UserBinder.getUserAccessService().getProperties();
userFilter = UserBinder.getUserAccessService().getFilterMap();
dirtyPropertiesMap = false;
columnUtil = this.new ColumnUtil();
if (UserBinder.getUserAccessService().getLocaleTag() != null) {
locale = Locale.forLanguageTag(UserBinder.getUserAccessService().getLocaleTag());
} else {
locale = Locale.forLanguageTag("en-US");
}
} else {
locale = Locale.forLanguageTag("en-US");
}
put(EventUtils.DATA, this);
put(userClass, IUser.class);
VaadinSession session = VaadinSession.getCurrent();
session.setAttribute(IUser.class, this);
transformerFactory = TransformerFactory.newInstance();
try {
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
LOGGER.error("transformer cannot be created {}", e);
}
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
dbf = DocumentBuilderFactory.newInstance(); //NOSONAR
dbf.setNamespaceAware(true);
try {
docBuilder = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
LOGGER.error("document builder cannot be created {}", e);
}
String sep = System.getProperty("file.separator");
String path = String.format("%s%s.osbee", System.getProperty("user.home"), sep);
new File(path).mkdirs();
filterFilePath = String.format("%s%sUser.filter", path, sep);
loadFilterDocument();
LOGGER.debug("User is initialized");
}
/**
* Gets the theme.
*
* @return the theme
*/
@Override
public String getTheme() {
return theme;
}
/**
* Gets the print service.
*
* @return the print service
*/
@Override
public String getPrintService() {
return printService;
}
/**
* Sets the print service.
*
* @param printService
* the new print service
*/
@Override
public void setPrintService(String printService) {
this.printService = printService;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.osbp.vaaclipse.publicapi.authentication.IUser#getUserName()
*/
@Override
public String getUserName() {
return userName;
}
/**
* Sets the user name.
*
* @param userName
* the new user name
*/
@Override
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String getProfileImageId() {
return profileImageId;
}
/**
* Gets the id.
*
* @return the id
*/
@Override
public String getId() {
return id;
}
/**
* Gets the position.
*
* @return the position
*/
@Override
public String getPosition() {
return position;
}
/**
* Gets the extra password.
*
* @return the extra password
*/
@Override
public String getExtraPassword() {
return extraPassword;
}
/**
* Gets the superuser.
*
* @return the superuser
*/
@Override
public boolean isSuperuser() {
return superuser;
}
/**
* Gets the perspective id.
*
* @return the perspective id
*/
@Override
public String getPerspective() {
return perspective;
}
/**
* Gets the email.
*
* @return the email
*/
@Override
public String getEmail() {
return email;
}
/**
* Gets the roles.
*
* @return the roles
*/
@Override
public Collection<String> getRoles() {
return roles;
}
/**
* Gets the locale.
*
* @return the locale
*/
@Override
public Locale getLocale() {
return locale;
}
/**
* Sets the locale.
*
* @param locale
* the new locale
*/
@Override
public void setLocale(Locale locale) {
this.locale = locale;
// force e4 application to switch locale and update localization
if (application != null) {
application.getContext().set(TranslationService.LOCALE, locale);
ApplicationLocalization.updateLocalization(application);
}
Locale.setDefault(locale);
notifyUserLocaleChanged(locale);
}
/**
* Gets the user access service.
*
* @return the user access service
*/
public IUserAccessService getUserAccessService() {
return UserBinder.getUserAccessService();
}
@Override
public void addUserLocaleListener(UserLocaleListener listener) {
if (listeners == null) {
listeners = new ArrayList<>();
}
if (!listeners.contains(listener)) {
listeners.add(listener);
if (locale != null) {
listener.localeChanged(locale);
}
}
}
@Override
public void removeUserLocaleListener(UserLocaleListener listener) {
if (listeners == null) {
return;
}
listeners.remove(listener);
}
@Override
public void notifyUserLocaleChanged(Locale locale) {
if (listeners == null) {
return;
}
for (UserLocaleListener listener : listeners.toArray(new UserLocaleListener[listeners.size()])) {
listener.localeChanged(locale);
}
}
@Override
public void setApplication(MApplication application) {
this.application = application;
setLocale(locale);
}
@Override
public Object getProperty (String key) {
return properties.get(key);
}
@Override
public void addToProperties (String key, Object value) {
properties.put(key, value);
dirtyPropertiesMap = true;
persistProperties();
}
@Override
public void removeFromProperties (String key) {
properties.remove(key);
dirtyPropertiesMap = true;
persistProperties();
}
@Override
public void persistProperties() {
if( dirtyPropertiesMap ) getUserAccessService().persistProperties(properties);
dirtyPropertiesMap = false;
}
@Override
public void clearFromProperties() {
properties.clear();
dirtyPropertiesMap = false;
}
/*
* Inner class as wrapper to the properties
*/
class ColumnUtil implements IColumnUtil{
@Override
public String getColumnWidth(String key) {
Object property = getProperty(key);
if (property instanceof String){
return (String)property;
}
return null;
}
@Override
public String getColumnCollapsed(String key) { // NOSONAR
Object property = getProperty(key);
if (property instanceof String){
return (String)property;
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public Map<Object, Integer> getVisibleColumns(String key) {
Object property = getProperty(key);
if (property instanceof Map<?, ?>){
return (Map<Object, Integer>)property;
}
return null;
}
}
@Override
public IColumnUtil getColumnUtil() {
return columnUtil;
}
@Override
public FilterMap getUserFilter() {
return userFilter;
}
@Override
public synchronized Document getFilterDocument() {
if(filterDocument == null) {
filterDocument = docBuilder.newDocument();
filterDocument.appendChild(filterDocument.createElement(IUser.docRoot));
}
return filterDocument;
}
@Override
public synchronized void loadFilterDocument() {
if(saveSettingsAsFile ) {
try(FileInputStream filterFile = new FileInputStream(filterFilePath)) {
filterDocument = docBuilder.parse(filterFile);
filterDocument.getDocumentElement().normalize();
} catch (IOException | SAXException e) {
LOGGER.error("{}", e);
}
} else {
String filters = UserBinder.getUserAccessService().getFilterSelections();
if(filters != null) {
try {
InputSource is = new InputSource(new StringReader(filters));
filterDocument = docBuilder.parse(is);
filterDocument.getDocumentElement().normalize();
} catch (IOException | SAXException e) {
LOGGER.error("{}", e);
}
}
}
}
@Override
public synchronized void saveFilterDocument() {
if(saveSettingsAsFile) {
try(FileOutputStream filterFile = new FileOutputStream(filterFilePath)) {
if(filterDocument != null) {
DOMSource source = new DOMSource(filterDocument);
FileWriter writer = new FileWriter(new File(filterFilePath));
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
writer.flush();
}
} catch (IOException | TransformerException e) {
LOGGER.error("{}", e);
}
} else {
try {
if(filterDocument != null) {
DOMSource source = new DOMSource(filterDocument);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
writer.flush();
String filters = writer.getBuffer().toString();
getUserAccessService().setFilterSelections(filters);
}
} catch (TransformerException e) {
LOGGER.error("{}", e);
}
}
}
@Override
public String loadDashboard() {
return UserBinder.getUserAccessService().getDashboard();
}
@Override
public void saveDashboard(String dashboard) {
UserBinder.getUserAccessService().setDashboard(dashboard);
}
@Override
public String loadFavorites() {
return UserBinder.getUserAccessService().getFavorites();
}
@Override
public void saveFavorites(String favorites) {
UserBinder.getUserAccessService().setFavorites(favorites);
}
}