Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • DM/dm-docs
  • hammonds/dm-docs
  • hparraga/dm-docs
3 results
Show changes
Showing
with 2609 additions and 0 deletions
package gov.anl.aps.dm.common.utilities;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* Dummy trust manager class.
*
* A trivial implementation of <code>X509TrustManager</code> that doesn't
* actually check the validity of a certificate. This allows us to make SSL
* connections to internal servers without requiring the installation and
* maintenance of certificates in the client keystore.
*
* @see NoServerVerificationSSLSocketFactory
*/
public class NoOpTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] cert, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] cert, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
package gov.anl.aps.dm.common.utilities;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.apache.log4j.Logger;
/**
* SSL socket factory that does not verify server credentials.
*
* A minor extension of <code>SSLSocketFactory</code> that installs a dummy
* trust manager. This allows creation of SSL sockets that don't verify the
* server certificates.
*
* @see NoOpTrustManager
*/
public class NoServerVerificationSSLSocketFactory extends SSLSocketFactory {
private static final Logger logger = Logger.getLogger(NoServerVerificationSSLSocketFactory.class.getName());
private SSLSocketFactory factory;
/**
* Default constructor.
*/
public NoServerVerificationSSLSocketFactory() {
try {
TrustManager tm = new NoOpTrustManager();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, // No KeyManager required
new TrustManager[]{tm},
new java.security.SecureRandom());
factory = (SSLSocketFactory) sslcontext.getSocketFactory();
} catch (KeyManagementException | NoSuchAlgorithmException ex) {
logger.error(ex);
}
}
/**
* Get default (no server verification) socket factory.
*
* @return socket factory
*/
public static SocketFactory getDefault() {
return new NoServerVerificationSSLSocketFactory();
}
/**
* Create SSL socket layered over an existing socket connected to the named
* host, at a given port.
*
* @param socket existing socket
* @param host
* @param port
* @param autoClose
* @return created socket
* @throws IOException in case of IO errors
*/
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException {
return factory.createSocket(socket, host, port, autoClose);
}
/**
* Create a socket and connect it to the specified remote address/port, and
* bind it to the specified local address/port.
*
* @param address server network address
* @param port server port
* @param localAddress client network address
* @param localPort client port
* @return created socket
* @throws IOException in case of IO errors
*/
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
throws IOException {
return factory.createSocket(address, port, localAddress, localPort);
}
/**
* Create a socket and connect it to the specified remote address/port.
*
* @param address server network address
* @param port server port
* @return created socket
* @throws IOException in case of IO errors
*/
@Override
public Socket createSocket(InetAddress address, int port) throws IOException {
return factory.createSocket(address, port);
}
/**
* Create a socket and connect it to the specified remote host/port, and
* bind it to the specified local address/port.
*
* @param host server host
* @param port server port
* @param localAddress client network address
* @param localPort client port
* @return created socket
* @throws IOException in case of IO errors
*/
@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort)
throws IOException {
return factory.createSocket(host, port, localAddress, localPort);
}
/**
* Create a socket and connect it to the specified remote host/port, and
* bind it to the specified local address/port.
*
* @param host server host
* @param port server port
* @return created socket
* @throws IOException in case of IO errors
*/
@Override
public Socket createSocket(String host, int port) throws IOException {
return factory.createSocket(host, port);
}
/**
* Get default cipher suites from socket factory.
*
* @return list of default ciphers
*/
@Override
public String[] getDefaultCipherSuites() {
return factory.getSupportedCipherSuites();
}
/**
* Get supported cipher suites from socket factory.
*
* @return list of supported ciphers
*/
@Override
public String[] getSupportedCipherSuites() {
return factory.getSupportedCipherSuites();
}
}
package gov.anl.aps.dm.common.utilities;
/**
* Object utility class.
*/
public class ObjectUtility {
/**
* Verify that two objects are the same.
*
* Object references can be null.
*
* @param <Type> template type of given objects
* @param object1 first object
* @param object2 second object
* @return true if objects are equal, false otherwise
*/
public static <Type> boolean equals(Type object1, Type object2) {
if (object1 == null && object2 == null) {
return true;
}
if (object1 == null || object2 == null) {
return false;
}
return object1.equals(object2);
}
}
package gov.anl.aps.dm.common.utilities;
/**
* String utility class.
*/
public class StringUtility {
/**
* Verify that two char sequences are the same.
*
* Input string references can be null.
*
* @param cs1 first sequence
* @param cs2 second sequence
* @return true if char sequences are the same, false otherwise
*/
public static boolean equals(CharSequence cs1, CharSequence cs2) {
if (cs1 == null && cs2 == null) {
return true;
}
if (cs1 == null || cs2 == null) {
return false;
}
return cs1.equals(cs2);
}
/**
* Capitalize first letter of a given string.
*
* @param input input string
* @return capitalized string
*/
public static String capitalize(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
}
package gov.anl.aps.dm.portal.constants;
/**
* Status codes.
*/
public class DmStatus
{
public static final int DM_OK = 0;
public static final int DM_ERROR = 1;
public static final int DM_DB_ERROR = 2;
public static final int DM_TIMEOUT = 3;
public static final int DM_INVALID_ARGUMENT = 4;
public static final int DM_INVALID_OBJECT_STATE = 5;
public static final int DM_OBJECT_ALREADY_EXISTS = 6;
public static final int DM_OBJECT_NOT_FOUND = 7;
public static final int DM_INVALID_DATE = 8;
public static final int DM_MISSING_PROPERTY = 9;
}
\ No newline at end of file
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.common.exceptions.DmException;
import gov.anl.aps.dm.common.exceptions.InvalidRequest;
import gov.anl.aps.dm.portal.model.beans.DmEntityDbFacade;
import gov.anl.aps.dm.portal.model.entities.DmEntity;
import gov.anl.aps.dm.common.utilities.CollectionUtility;
import gov.anl.aps.dm.common.utilities.StringUtility;
import gov.anl.aps.dm.portal.utilities.SessionUtility;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import org.primefaces.event.data.FilterEvent;
public abstract class DmEntityController<EntityType extends DmEntity, FacadeType extends DmEntityDbFacade<EntityType>> implements Serializable {
private static final Logger logger = Logger.getLogger(DmEntityController.class.getName());
private static final int NUMBER_OF_ROWS_FOR_DISPLAY_LIST = 25;
private static final int NUMBER_OF_ROWS_FOR_SELECT_LIST = 10;
protected EntityType current = null;
private DataModel listDataModel = null;
private List<EntityType> filteredObjectList = null;
private DataModel selectDataModel = null;
private List<EntityType> selectedObjectList = null;
private int displayNumberOfItemsPerPage = NUMBER_OF_ROWS_FOR_DISPLAY_LIST;
private int selectNumberOfItemsPerPage = NUMBER_OF_ROWS_FOR_SELECT_LIST;
protected String breadcrumbViewParam = null;
protected String breadcrumbObjectIdViewParam = null;
public DmEntityController() {
}
@PostConstruct
public void initialize() {
}
/**
* Navigate to invalid request error page.
*
* @param error error message
*/
public void handleInvalidSessionRequest(String error) {
SessionUtility.setLastSessionError(error);
SessionUtility.navigateTo("/views/error/invalidRequest?faces-redirect=true");
}
protected abstract FacadeType getFacade();
protected abstract EntityType createEntityInstance();
public abstract String getEntityTypeName();
public String getDisplayEntityTypeName() {
return getEntityTypeName();
}
public abstract String getCurrentEntityInstanceName();
public EntityType getCurrent() {
return current;
}
public void setCurrent(EntityType current) {
this.current = current;
}
/**
* Find entity instance by id.
*
* @param id entity instance id
* @return entity instance
*/
public EntityType findById(Integer id) {
return null;
}
public void selectByRequestParams() {
}
public EntityType getSelected() {
if (current == null) {
current = createEntityInstance();
}
return current;
}
public boolean isEntitySelected() {
return (current != null);
}
public void onFilterChange(FilterEvent filterEvent) {
}
/**
* Clear entity list filters.
*
* This method should be overridden in any derived controller class that has
* its own filters.
*/
public void clearListFilters() {
}
/**
* Clear entity selection list filters.
*
* This method should be overridden in any derived controller class that has
* its own select filters.
*/
public void clearSelectFilters() {
}
public String resetList() {
logger.debug("Resetting list data model for " + getDisplayEntityTypeName());
clearListFilters();
resetListDataModel();
return prepareList();
}
public String prepareList() {
logger.debug("Preparing list data model for " + getDisplayEntityTypeName());
current = null;
return "list?faces-redirect=true";
}
/**
* Process view request parameters.
*
* If request is not valid, user will be redirected to appropriate error
* page.
*/
public void processViewRequestParams() {
try {
EntityType entity = selectByViewRequestParams();
if (entity != null) {
prepareEntityView(entity);
}
} catch (DmException ex) {
handleInvalidSessionRequest(ex.getErrorMessage());
}
}
/**
* Set breadcrumb variables from request parameters.
*/
protected void setBreadcrumbRequestParams() {
if (breadcrumbViewParam == null) {
breadcrumbViewParam = SessionUtility.getRequestParameterValue("breadcrumb");
}
if (breadcrumbObjectIdViewParam == null) {
breadcrumbObjectIdViewParam = SessionUtility.getRequestParameterValue("breadcrumbObjectId");
}
}
/**
* Select current entity instance for view from request parameters.
*
* @return selected entity instance
* @throws DmException in case of invalid request parameter values
*/
public EntityType selectByViewRequestParams() throws DmException {
setBreadcrumbRequestParams();
Integer idParam = null;
String paramValue = SessionUtility.getRequestParameterValue("id");
try {
if (paramValue != null) {
idParam = Integer.parseInt(paramValue);
}
} catch (NumberFormatException ex) {
throw new InvalidRequest("Invalid value supplied for " + getDisplayEntityTypeName() + " id: " + paramValue);
}
if (idParam != null) {
EntityType entity = findById(idParam);
if (entity == null) {
throw new InvalidRequest(StringUtility.capitalize(getDisplayEntityTypeName()) + " id " + idParam + " does not exist.");
}
setCurrent(entity);
return entity;
} else if (current == null || current.getId() == null) {
throw new InvalidRequest(StringUtility.capitalize(getDisplayEntityTypeName()) + " has not been selected.");
}
return current;
}
/**
* Follow breadcrumb if it is set, or prepare entity list view.
*
* @return previous view if breadcrumb parameters are set, or entity list
* view otherwise
*/
public String followBreadcrumbOrPrepareList() {
String loadView = breadcrumbViewParam;
if (loadView == null) {
loadView = prepareList();
} else {
if (breadcrumbObjectIdViewParam != null) {
Integer entityId = Integer.parseInt(breadcrumbObjectIdViewParam);
loadView = breadcrumbViewParam + "?faces-redirect=true&id=" + entityId;
}
}
breadcrumbViewParam = null;
breadcrumbObjectIdViewParam = null;
return loadView;
}
public String prepareView(EntityType entity) {
logger.debug("Preparing view for " + entity.toString());
current = entity;
prepareEntityView(entity);
return view();
}
protected void prepareEntityView(EntityType entity) {
}
public void clear() {
}
public String view() {
return "view?faces-redirect=true";
}
public String prepareCreate() {
current = createEntityInstance();
return "create?faces-redirect=true";
}
protected void prepareEntityInsert(EntityType entity) throws DmException {
}
public String create() {
try {
EntityType newEntity = current;
prepareEntityInsert(current);
getFacade().create(current);
SessionUtility.addInfoMessage("Success", "Created " + getDisplayEntityTypeName() + " " + getCurrentEntityInstanceName() + ".");
resetListDataModel();
current = newEntity;
return prepareList();
} catch (DmException | RuntimeException ex) {
SessionUtility.addErrorMessage("Error", "Could not create " + getDisplayEntityTypeName() + ": " + ex.getMessage());
return null;
}
}
public String prepareEdit(EntityType entity) {
current = entity;
return edit();
}
public String edit() {
resetSelectDataModel();
return "edit?faces-redirect=true";
}
protected void prepareEntityUpdate(EntityType entity) throws DmException {
}
public String update() {
try {
logger.debug("Updating " + getDisplayEntityTypeName() + " " + getCurrentEntityInstanceName());
EntityType updatedEntity = current;
prepareEntityUpdate(updatedEntity);
getFacade().edit(updatedEntity);
SessionUtility.addInfoMessage("Success", "Updated " + getDisplayEntityTypeName() + " " + getCurrentEntityInstanceName() + ".");
resetListDataModel();
current = updatedEntity;
return view();
} catch (DmException ex) {
SessionUtility.addErrorMessage("Error", "Could not update " + getDisplayEntityTypeName() + ": " + ex.getMessage());
return null;
} catch (RuntimeException ex) {
SessionUtility.addErrorMessage("Error", "Could not update " + getDisplayEntityTypeName() + ": " + getObjectAlreadyExistMessage(current));
return null;
}
}
protected String getObjectAlreadyExistMessage(EntityType entity) {
return "";
}
protected void prepareEntityUpdateOnRemoval(EntityType entity) throws DmException {
}
public String updateOnRemoval() {
try {
logger.debug("Updating " + getDisplayEntityTypeName() + " " + getCurrentEntityInstanceName());
prepareEntityUpdateOnRemoval(current);
getFacade().edit(current);
EntityType updatedEntity = current;
SessionUtility.addInfoMessage("Success", "Updated " + getDisplayEntityTypeName() + " " + getCurrentEntityInstanceName() + ".");
resetListDataModel();
resetSelectDataModel();
current = updatedEntity;
return view();
} catch (DmException ex) {
SessionUtility.addErrorMessage("Error", "Could not update " + getDisplayEntityTypeName() + ": " + ex.getMessage());
return null;
} catch (RuntimeException ex) {
logger.error("Could not update " + getDisplayEntityTypeName() + " "
+ getCurrentEntityInstanceName() + ": " + ex.getMessage());
SessionUtility.addErrorMessage("Error", "Could not update " + getDisplayEntityTypeName() + ": " + ex.getMessage());
return null;
}
}
protected void prepareEntityDestroy(EntityType entity) throws DmException {
}
public void destroy(EntityType entity) {
current = entity;
destroy();
}
public String destroy() {
if (current == null) {
logger.warn("Current item is not set");
// Do nothing if current item is not set.
return null;
}
try {
logger.debug("Destroying " + getCurrentEntityInstanceName());
getFacade().remove(current);
SessionUtility.addInfoMessage("Success", "Deleted " + getDisplayEntityTypeName() + " " + getCurrentEntityInstanceName() + ".");
resetListDataModel();
return prepareList();
} catch (Exception ex) {
SessionUtility.addErrorMessage("Error", "Could not delete " + getDisplayEntityTypeName() + ": " + ex.getMessage());
return null;
}
}
public DataModel createListDataModel() {
return new ListDataModel(getFacade().findAll());
}
public DataModel getListDataModel() {
if (listDataModel == null) {
listDataModel = createListDataModel();
}
return listDataModel;
}
public void prepareEntityListForSelection(List<EntityType> selectEntityList) {
}
public DataModel createSelectDataModel() {
List<EntityType> selectEntityList = getFacade().findAll();
prepareEntityListForSelection(selectEntityList);
return new ListDataModel(selectEntityList);
}
public DataModel getSelectDataModel() {
if (selectDataModel == null) {
selectDataModel = createSelectDataModel();
}
return selectDataModel;
}
public DataModel getItems() {
return getListDataModel();
}
public List<EntityType> getSelectedObjectListAndResetSelectDataModel() {
List<EntityType> returnList = selectedObjectList;
resetSelectDataModel();
return returnList;
}
public List<EntityType> getSelectedObjectList() {
return selectedObjectList;
}
public List<EntityType> getFilteredObjectList() {
return filteredObjectList;
}
public List<EntityType> getFilteredItems() {
return filteredObjectList;
}
public void resetSelectedObjectList() {
selectedObjectList = null;
}
public void setSelectedObjectList(List<EntityType> selectedObjectList) {
this.selectedObjectList = selectedObjectList;
}
public void setFilteredObjectList(List<EntityType> filteredObjectList) {
this.filteredObjectList = filteredObjectList;
}
public void setFilteredItems(List<EntityType> filteredItems) {
this.filteredObjectList = filteredItems;
}
public void resetListDataModel() {
listDataModel = null;
filteredObjectList = null;
current = null;
}
public void resetSelectDataModel() {
selectDataModel = null;
selectedObjectList = null;
}
public List<EntityType> getAvailableItems() {
return getFacade().findAll();
}
public EntityType getEntity(Integer id) {
return getFacade().find(id);
}
public SelectItem[] getAvailableItemsForSelectMany() {
return CollectionUtility.getSelectItems(getFacade().findAll(), false);
}
public SelectItem[] getAvailableItemsForSelectOne() {
return CollectionUtility.getSelectItems(getFacade().findAll(), true);
}
public String getCurrentViewId() {
return SessionUtility.getCurrentViewId();
}
public static String displayEntityList(List<?> entityList) {
String itemDelimiter = ", ";
return CollectionUtility.displayItemListWithoutOutsideDelimiters(entityList, itemDelimiter);
}
public int getDisplayNumberOfItemsPerPage() {
return displayNumberOfItemsPerPage;
}
public void setDisplayNumberOfItemsPerPage(int displayNumberOfItemsPerPage) {
this.displayNumberOfItemsPerPage = displayNumberOfItemsPerPage;
}
public int getSelectNumberOfItemsPerPage() {
return selectNumberOfItemsPerPage;
}
public void setSelectNumberOfItemsPerPage(int selectNumberOfItemsPerPage) {
this.selectNumberOfItemsPerPage = selectNumberOfItemsPerPage;
}
}
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.api.ExperimentDsApi;
import gov.anl.aps.dm.common.exceptions.DmException;
import gov.anl.aps.dm.common.exceptions.ObjectAlreadyExists;
import gov.anl.aps.dm.common.exceptions.InvalidRequest;
import gov.anl.aps.dm.portal.model.entities.Experiment;
import gov.anl.aps.dm.portal.model.beans.ExperimentDbFacade;
import gov.anl.aps.dm.portal.model.beans.ExperimentRoleTypeDbFacade;
import gov.anl.aps.dm.portal.model.beans.UserExperimentRoleDbFacade;
import gov.anl.aps.dm.portal.model.entities.ExperimentRoleType;
import gov.anl.aps.dm.portal.model.entities.ExperimentStation;
import gov.anl.aps.dm.portal.model.entities.UserExperimentRole;
import gov.anl.aps.dm.portal.model.entities.UserExperimentRolePK;
import gov.anl.aps.dm.portal.model.entities.UserInfo;
import gov.anl.aps.dm.portal.utilities.DmApiFactory;
import gov.anl.aps.dm.portal.utilities.SessionUtility;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.apache.log4j.Logger;
@Named("experimentController")
@SessionScoped
public class ExperimentController extends DmEntityController<Experiment, ExperimentDbFacade> {
private static final Logger logger = Logger.getLogger(ExperimentController.class.getName());
@EJB
private ExperimentDbFacade experimentDbFacade;
@EJB
private UserExperimentRoleDbFacade userExperimentRoleDbFacade;
@EJB
private ExperimentRoleTypeDbFacade experimentRoleTypeDbFacade;
private UserExperimentRole currentUserExperimentRole = null;
private Experiment currentStationExperiment = null;
private String filterByName = null;
private String filterByType = null;
private String filterByStation = null;
private String filterByDescription = null;
private String filterByStartDate = null;
private String filterByEndDate = null;
private String selectFilterByName = null;
private String selectFilterByType = null;
private String selectFilterByStation = null;
private String selectFilterByDescription = null;
private String selectFilterByStartDate = null;
private String selectFilterByEndDate = null;
public ExperimentController() {
}
@Override
protected ExperimentDbFacade getFacade() {
return experimentDbFacade;
}
@Override
protected Experiment createEntityInstance() {
Experiment newExperiment = new Experiment();
return newExperiment;
}
@Override
public String getEntityTypeName() {
return "experiment";
}
@Override
public String getCurrentEntityInstanceName() {
if (getCurrent() != null) {
return getCurrent().getName();
}
return "";
}
@Override
public Experiment findById(Integer id) {
return experimentDbFacade.findById(id);
}
@Override
public void prepareEntityInsert(Experiment experiment) throws DmException {
if ((experiment.getName() == null) || (experiment.getName().length() == 0)) {
throw new InvalidRequest("Experiment name is missing.");
}
Experiment existingExperiment = experimentDbFacade.findByName(experiment.getName());
if (existingExperiment != null) {
throw new ObjectAlreadyExists("Experiment " + experiment.getName() + " already exists.");
}
verifyExperiment(experiment);
logger.debug("Inserting new experiment " + experiment.getName());
}
@Override
public void prepareEntityUpdate(Experiment experiment) throws DmException {
if ((experiment.getName() == null) || (experiment.getName().length() == 0)) {
throw new InvalidRequest("Experiment name is missing.");
}
verifyExperiment(experiment);
logger.debug("Updating experiment " + experiment.getName());
}
@Override
protected String getObjectAlreadyExistMessage(Experiment experiment) {
if (experiment == null) {
return null;
}
return "Experiment " + experiment.getName() + " already exists.";
}
private void verifyExperiment(Experiment experiment) throws DmException {
if (experiment.getExperimentType() == null) {
throw new InvalidRequest("Experiment type is missing.");
}
if (experiment.getExperimentStation() == null) {
throw new InvalidRequest("Experiment station is missing.");
}
if ((experiment.getStartDate() != null) && (experiment.getEndDate() != null) && (experiment.getEndDate().before(experiment.getStartDate()))) {
throw new InvalidRequest("Experiment end date is before start date.");
}
}
@Override
public String update() {
// Notify DS Web Service
try {
ExperimentDsApi api = DmApiFactory.getExperimentDsApi();
api.updateExperiment(getCurrent().getName());
} catch (DmException ex) {
logger.error("Could not notify Data Storage Service: " + ex);
SessionUtility.addErrorMessage("Error", "Unable to notify Data Storage Service: " + ex.getErrorMessage());
}
clear();
return super.update();
}
public UserExperimentRole getCurrentUserExperimentRole() {
if (currentUserExperimentRole == null) {
currentUserExperimentRole = new UserExperimentRole();
}
return currentUserExperimentRole;
}
public void setCurrentUserExperimentRole(UserExperimentRole currentUserExperimentRole) {
this.currentUserExperimentRole = currentUserExperimentRole;
}
public void prepareAddUserExperimentRole(Experiment experiment) {
UserExperimentRole userExperimentRole = getCurrentUserExperimentRole();
userExperimentRole.setExperiment(experiment);
}
private void addUserExperimentRole() {
UserInfo user = currentUserExperimentRole.getUserInfo();
Experiment experiment = currentUserExperimentRole.getExperiment();
ExperimentRoleType roleType = currentUserExperimentRole.getExperimentRoleType();
UserExperimentRolePK userExperimentRolePK = new UserExperimentRolePK();
userExperimentRolePK.setExperimentId(experiment.getId());
userExperimentRolePK.setUserId(user.getId());
userExperimentRolePK.setRoleTypeId(roleType.getId());
currentUserExperimentRole.setUserExperimentRolePK(userExperimentRolePK);
UserExperimentRole existingRole = userExperimentRoleDbFacade.findByUserAndExperiment(user.getId(),
experiment.getId());
if (existingRole != null) {
SessionUtility.addErrorMessage("Error", "Could not add experiment user: User "
+ user.getUsername()
+ " is already associated with experiment "
+ existingRole.getExperiment().getName() + " as "
+ existingRole.getExperimentRoleType().getName() + ".");
return;
}
List<UserExperimentRole> userExperimentRoleList = experiment.getUserExperimentRoleList();
userExperimentRoleList.add(0, currentUserExperimentRole);
update();
currentUserExperimentRole = null;
}
public void addUserExperimentRolePi() {
currentUserExperimentRole.setExperimentRoleType(experimentRoleTypeDbFacade.findPiRoleType());
addUserExperimentRole();
}
public void addUserExperimentRoleUser() {
currentUserExperimentRole.setExperimentRoleType(experimentRoleTypeDbFacade.findUserRoleType());
addUserExperimentRole();
}
public void deleteUserExperimentRole(UserExperimentRole userExperimentRole) {
Experiment experiment = getCurrent();
userExperimentRoleDbFacade.remove(userExperimentRole);
List<UserExperimentRole> userExperimentRoleList = experiment.getUserExperimentRoleList();
userExperimentRoleList.remove(userExperimentRole);
updateOnRemoval();
}
public Experiment getCurrentStationExperiment() {
if (currentStationExperiment == null) {
currentStationExperiment = new Experiment();
}
return currentStationExperiment;
}
public void setCurrentStationExperiment(Experiment currentStationExperiment) {
this.currentStationExperiment = currentStationExperiment;
}
public void prepareAddStationExperiment(ExperimentStation experimentStation) {
currentStationExperiment = getCurrentStationExperiment();
currentStationExperiment.setExperimentStation(experimentStation);
}
public void addStationExperiment() {
try {
prepareEntityInsert(currentStationExperiment);
getFacade().create(currentStationExperiment);
SessionUtility.addInfoMessage("Success", "Created experiment " + currentStationExperiment.getName() + ".");
resetListDataModel();
current = currentStationExperiment;
List<Experiment> stationExperimentList = currentStationExperiment.getExperimentStation().getExperimentList();
stationExperimentList.add(0, currentStationExperiment);
currentStationExperiment = null;
} catch (DmException | RuntimeException ex) {
SessionUtility.addErrorMessage("Error", "Could not create experiment: " + ex.getMessage());
}
}
public void deleteStationExperiment(Experiment stationExperiment) {
List<Experiment> stationExperimentList = stationExperiment.getExperimentStation().getExperimentList();
stationExperimentList.remove(stationExperiment);
destroy(stationExperiment);
}
@Override
public void clearListFilters() {
filterByName = null;
filterByType = null;
filterByStation = null;
filterByDescription = null;
filterByStartDate = null;
filterByEndDate = null;
}
@Override
public void clearSelectFilters() {
selectFilterByName = null;
selectFilterByType = null;
selectFilterByStation = null;
selectFilterByDescription = null;
selectFilterByStartDate = null;
selectFilterByEndDate = null;
}
public String getFilterByName() {
return filterByName;
}
public void setFilterByName(String filterByName) {
this.filterByName = filterByName;
}
public String getFilterByType() {
return filterByType;
}
public void setFilterByType(String filterByType) {
this.filterByType = filterByType;
}
public String getFilterByStation() {
return filterByStation;
}
public void setFilterByStation(String filterByStation) {
this.filterByStation = filterByStation;
}
public String getFilterByDescription() {
return filterByDescription;
}
public void setFilterByDescription(String filterByDescription) {
this.filterByDescription = filterByDescription;
}
public String getFilterByStartDate() {
return filterByStartDate;
}
public void setFilterByStartDate(String filterByStartDate) {
this.filterByStartDate = filterByStartDate;
}
public String getFilterByEndDate() {
return filterByEndDate;
}
public void setFilterByEndDate(String filterByEndDate) {
this.filterByEndDate = filterByEndDate;
}
public String getSelectFilterByName() {
return selectFilterByName;
}
public void setSelectFilterByName(String selectFilterByName) {
this.selectFilterByName = selectFilterByName;
}
public String getSelectFilterByType() {
return selectFilterByType;
}
public void setSelectFilterByType(String selectFilterByType) {
this.selectFilterByType = selectFilterByType;
}
public String getSelectFilterByStation() {
return selectFilterByStation;
}
public void setSelectFilterByStation(String selectFilterByStation) {
this.selectFilterByStation = selectFilterByStation;
}
public String getSelectFilterByDescription() {
return selectFilterByDescription;
}
public void setSelectFilterByDescription(String selectFilterByDescription) {
this.selectFilterByDescription = selectFilterByDescription;
}
public String getSelectFilterByStartDate() {
return selectFilterByStartDate;
}
public void setSelectFilterByStartDate(String selectFilterByStartDate) {
this.selectFilterByStartDate = selectFilterByStartDate;
}
public String getSelectFilterByEndDate() {
return selectFilterByEndDate;
}
public void setSelectFilterByEndDate(String selectFilterByEndDate) {
this.selectFilterByEndDate = selectFilterByEndDate;
}
@FacesConverter(forClass = Experiment.class)
public static class ExperimentControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ExperimentController controller = (ExperimentController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "experimentController");
return controller.getEntity(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Experiment) {
Experiment o = (Experiment) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("Object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Experiment.class.getName());
}
}
}
}
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.portal.model.beans.ExperimentRoleTypeDbFacade;
import gov.anl.aps.dm.portal.model.entities.ExperimentRoleType;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.apache.log4j.Logger;
@Named("experimentRoleTypeController")
@SessionScoped
public class ExperimentRoleTypeController extends DmEntityController<ExperimentRoleType, ExperimentRoleTypeDbFacade> {
private static final Logger logger = Logger.getLogger(ExperimentRoleTypeController.class.getName());
@EJB
private ExperimentRoleTypeDbFacade experimentRoleTypeDbFacade;
public ExperimentRoleTypeController() {
}
@Override
protected ExperimentRoleTypeDbFacade getFacade() {
return experimentRoleTypeDbFacade;
}
@Override
protected ExperimentRoleType createEntityInstance() {
return new ExperimentRoleType();
}
@Override
public String getEntityTypeName() {
return "experimentRoleType";
}
@Override
public String getCurrentEntityInstanceName() {
if (getCurrent() != null) {
return getCurrent().getName();
}
return "";
}
@Override
public ExperimentRoleType findById(Integer id) {
return experimentRoleTypeDbFacade.findById(id);
}
@FacesConverter(forClass = ExperimentRoleType.class)
public static class ExperimentRoleTypeControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ExperimentRoleTypeController controller = (ExperimentRoleTypeController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "experimentRoleTypeController");
return controller.getEntity(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof ExperimentRoleType) {
ExperimentRoleType o = (ExperimentRoleType) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("Object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ExperimentRoleType.class.getName());
}
}
}
}
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.common.exceptions.DmException;
import gov.anl.aps.dm.common.exceptions.InvalidRequest;
import gov.anl.aps.dm.common.exceptions.ObjectAlreadyExists;
import gov.anl.aps.dm.portal.model.beans.ExperimentStationDbFacade;
import gov.anl.aps.dm.portal.model.beans.SystemRoleTypeDbFacade;
import gov.anl.aps.dm.portal.model.beans.UserSystemRoleDbFacade;
import gov.anl.aps.dm.portal.model.entities.ExperimentStation;
import gov.anl.aps.dm.portal.model.entities.SystemRoleType;
import gov.anl.aps.dm.portal.model.entities.UserInfo;
import gov.anl.aps.dm.portal.model.entities.UserSystemRole;
import gov.anl.aps.dm.portal.model.entities.UserSystemRolePK;
import gov.anl.aps.dm.portal.utilities.AuthorizationUtility;
import gov.anl.aps.dm.portal.utilities.SessionUtility;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.apache.log4j.Logger;
@Named("experimentStationController")
@SessionScoped
public class ExperimentStationController extends DmEntityController<ExperimentStation, ExperimentStationDbFacade> {
private static final Logger logger = Logger.getLogger(ExperimentStationController.class.getName());
@EJB
private ExperimentStationDbFacade experimentStationDbFacade;
@EJB
private SystemRoleTypeDbFacade systemRoleTypeDbFacade;
@EJB
private UserSystemRoleDbFacade userSystemRoleDbFacade;
UserSystemRole currentUserSystemRole;
public ExperimentStationController() {
}
@Override
protected ExperimentStationDbFacade getFacade() {
return experimentStationDbFacade;
}
@Override
protected ExperimentStation createEntityInstance() {
return new ExperimentStation();
}
@Override
public String getEntityTypeName() {
return "experimentStation";
}
@Override
public String getCurrentEntityInstanceName() {
if (getCurrent() != null) {
return getCurrent().getName();
}
return "";
}
@Override
public ExperimentStation findById(Integer id) {
return experimentStationDbFacade.findById(id);
}
@Override
public void prepareEntityInsert(ExperimentStation experimentStation) throws DmException {
if ((experimentStation.getName() == null) || (experimentStation.getName().length() == 0)) {
throw new InvalidRequest("Experiment station name is missing.");
}
ExperimentStation existingExperimentStation = experimentStationDbFacade.findByName(experimentStation.getName());
if (existingExperimentStation != null) {
throw new ObjectAlreadyExists("Experiment station " + experimentStation.getName() + " already exists.");
}
logger.debug("Inserting new experiment station " + experimentStation.getName());
}
@Override
public void prepareEntityUpdate(ExperimentStation experimentStation) throws DmException {
if ((experimentStation.getName() == null) || (experimentStation.getName().length() == 0)) {
throw new InvalidRequest("Experiment station name is missing.");
}
logger.debug("Updating experiment station " + experimentStation.getName());
}
@Override
protected String getObjectAlreadyExistMessage(ExperimentStation experimentStation) {
if (experimentStation == null) {
return null;
}
return "Experiment station " + experimentStation.getName() + " already exists.";
}
public List<ExperimentStation> getAvailableExperimentStations() {
UserInfo user = (UserInfo) SessionUtility.getUser();
if (AuthorizationUtility.isAdministrator(user)) {
return getFacade().findAll();
}
ArrayList<ExperimentStation> availableStations = new ArrayList<>();
user.getUserSystemRoleList().stream().map((userSystemRole) -> userSystemRole.getExperimentStation()).filter((experimentStation) -> (experimentStation != null)).forEachOrdered((experimentStation) -> {
availableStations.add(experimentStation);
});
return availableStations;
}
public UserSystemRole getCurrentUserSystemRole() {
if (currentUserSystemRole == null) {
currentUserSystemRole = new UserSystemRole();
}
return currentUserSystemRole;
}
public void setCurrentUserSystemRole(UserSystemRole currentUserSystemRole) {
this.currentUserSystemRole = currentUserSystemRole;
}
public void prepareAddManager(ExperimentStation experimentStation) {
UserSystemRole userSystemRole = getCurrentUserSystemRole();
userSystemRole.setSystemRoleType(systemRoleTypeDbFacade.findManagerRoleType());
userSystemRole.setExperimentStation(experimentStation);
}
public void addManager() {
UserInfo user = currentUserSystemRole.getUserInfo();
ExperimentStation experimentStation = currentUserSystemRole.getExperimentStation();
SystemRoleType roleType = currentUserSystemRole.getSystemRoleType();
UserSystemRolePK userSystemRolePK = new UserSystemRolePK();
userSystemRolePK.setUserId(user.getId());
userSystemRolePK.setRoleTypeId(roleType.getId());
currentUserSystemRole.setUserSystemRolePK(userSystemRolePK);
UserSystemRole existingRole = userSystemRoleDbFacade.findByUserAndRoleTypeAndExperimentStation(user.getId(),
roleType.getId(), experimentStation.getId());
if (existingRole != null) {
SessionUtility.addErrorMessage("Error", "Could not add station manager: User "
+ user.getUsername()
+ " is already as manager of "
+ experimentStation.getName() + " station.");
return;
}
List<UserSystemRole> userSystemRoleList = experimentStation.getUserSystemRoleList();
userSystemRoleList.add(0, currentUserSystemRole);
update();
currentUserSystemRole = null;
}
public void deleteManager(UserSystemRole userSystemRole) {
ExperimentStation experimentStation = getCurrent();
userSystemRoleDbFacade.remove(userSystemRole);
List<UserSystemRole> userSystemRoleList = experimentStation.getUserSystemRoleList();
userSystemRoleList.remove(userSystemRole);
updateOnRemoval();
}
@FacesConverter(forClass = ExperimentStation.class)
public static class ExperimentStationControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ExperimentStationController controller = (ExperimentStationController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "experimentStationController");
return controller.getEntity(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof ExperimentStation) {
ExperimentStation o = (ExperimentStation) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("Object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ExperimentStation.class.getName());
}
}
}
}
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.common.exceptions.DmException;
import gov.anl.aps.dm.common.exceptions.InvalidRequest;
import gov.anl.aps.dm.common.exceptions.ObjectAlreadyExists;
import gov.anl.aps.dm.portal.model.beans.ExperimentTypeDbFacade;
import gov.anl.aps.dm.portal.model.entities.ExperimentType;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.apache.log4j.Logger;
@Named("experimentTypeController")
@SessionScoped
public class ExperimentTypeController extends DmEntityController<ExperimentType, ExperimentTypeDbFacade> {
private static final Logger logger = Logger.getLogger(ExperimentTypeController.class.getName());
@EJB
private ExperimentTypeDbFacade experimentTypeDbFacade;
public ExperimentTypeController() {
}
@Override
protected ExperimentTypeDbFacade getFacade() {
return experimentTypeDbFacade;
}
@Override
protected ExperimentType createEntityInstance() {
return new ExperimentType();
}
@Override
public String getEntityTypeName() {
return "experimentType";
}
@Override
public String getCurrentEntityInstanceName() {
if (getCurrent() != null) {
return getCurrent().getName();
}
return "";
}
@Override
public ExperimentType findById(Integer id) {
return experimentTypeDbFacade.findById(id);
}
@Override
public void prepareEntityInsert(ExperimentType experimentType) throws DmException {
if ((experimentType.getName() == null) || (experimentType.getName().length() == 0)) {
throw new InvalidRequest("Experiment type name is missing.");
}
ExperimentType existingExperimentType = experimentTypeDbFacade.findByName(experimentType.getName());
if (existingExperimentType != null) {
throw new ObjectAlreadyExists("Experiment type " + experimentType.getName() + " already exists.");
}
logger.debug("Inserting new experiment type " + experimentType.getName());
}
@Override
public void prepareEntityUpdate(ExperimentType experimentType) throws DmException {
if ((experimentType.getName() == null) || (experimentType.getName().length() == 0)) {
throw new InvalidRequest("Experiment type name is missing.");
}
logger.debug("Updating experiment type " + experimentType.getName());
}
@Override
protected String getObjectAlreadyExistMessage(ExperimentType experimentType) {
if (experimentType == null) {
return null;
}
return "Experiment type " + experimentType.getName() + " already exists.";
}
@FacesConverter(forClass = ExperimentType.class)
public static class ExperimentTypeControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ExperimentTypeController controller = (ExperimentTypeController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "experimentTypeController");
return controller.getEntity(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof ExperimentType) {
ExperimentType o = (ExperimentType) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("Object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ExperimentType.class.getName());
}
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.portal.model.beans.UserInfoDbFacade;
import gov.anl.aps.dm.portal.model.entities.UserInfo;
import gov.anl.aps.dm.common.utilities.CryptUtility;
import gov.anl.aps.dm.common.utilities.LdapUtility;
import gov.anl.aps.dm.portal.model.entities.Experiment;
import gov.anl.aps.dm.portal.model.entities.ExperimentStation;
import gov.anl.aps.dm.portal.utilities.AuthorizationUtility;
import gov.anl.aps.dm.portal.utilities.SessionUtility;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.apache.log4j.Logger;
/**
* Login controller.
*/
@Named("loginController")
@SessionScoped
public class LoginController implements Serializable {
@EJB
private UserInfoDbFacade userInfoFacade;
private String username = null;
private String password = null;
private boolean loggedIn = false;
private UserInfo user = null;
private boolean isAdmin;
private static final Logger logger = Logger.getLogger(LoginController.class.getName());
/**
* Constructor.
*/
public LoginController() {
}
/**
* Get password.
*
* @return login password
*/
public String getPassword() {
return password;
}
/**
* Set password.
*
* @param password login password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Get username.
*
* @return login username
*/
public String getUsername() {
return username;
}
/**
* Set username.
*
* @param username login username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Check if user is logged in.
*
* @return true if admin is logged in, false otherwise
*/
public boolean isLoggedIn() {
return loggedIn;
}
/**
* Login action.
*
* @return url to service home page if login is successful, or null in case
* of errors
*/
public String login() {
loggedIn = false;
if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
SessionUtility.addWarningMessage(null, "Incomplete Input. Please enter both username and password.");
return (username = password = null);
}
user = userInfoFacade.findByUsername(username);
if (user == null) {
SessionUtility.addErrorMessage(null, "Username " + username + " is not registered. Contact administrator.");
return (username = password = null);
}
boolean validCredentials = false;
if (user.getPassword() != null && CryptUtility.verifyPasswordWithPbkdf2(password, user.getPassword())) {
logger.debug("User " + username + " is authorized by DM DB");
validCredentials = true;
} else if (LdapUtility.validateCredentials(username, password)) {
logger.debug("User " + username + " is authorized by DM LDAP");
validCredentials = true;
} else {
logger.debug("User " + username + " is not authorized.");
}
if (validCredentials) {
SessionUtility.setUser(user);
loggedIn = true;
SessionUtility.addInfoMessage("Successful Login", "User " + username + " is logged in.");
isAdmin = AuthorizationUtility.isAdministrator(user);
return getLandingPage();
} else {
SessionUtility.addErrorMessage(null, "Invalid Credentials. Username/password combination could not be verified.");
SessionUtility.addErrorMessage(null, "If you are having difficulty logging in, please see our <a href=\"/dm/views/loginHelp.xhtml\">login help</a> page.");
return (username = password = null);
}
}
public String getLandingPage() {
String landingPage = SessionUtility.getCurrentViewId() + "?faces-redirect=true";
if (landingPage.contains("login")) {
landingPage = "/views/home?faces-redirect=true";
}
logger.debug("Landing page: " + landingPage);
return landingPage;
}
public String displayUsername() {
if (isLoggedIn()) {
return username;
} else {
return "Not Logged In";
}
}
public String displayRole() {
if (isAdmin()) {
return "Administrator";
} else {
return "User";
}
}
/**
* Logout action.
*
* @return url to logout page
*/
public String logout() {
SessionUtility.clearSession();
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
context.invalidateSession();
loggedIn = false;
user = null;
return "/views/login?faces-redirect=true";
}
public boolean isAdmin() {
return isAdmin;
}
public boolean isAdministrator() {
return AuthorizationUtility.isAdministrator(user);
}
public boolean isStationManager(ExperimentStation experimentStation) {
return AuthorizationUtility.isStationManager(user, experimentStation);
}
public boolean isExperimentPi(Experiment experiment) {
return AuthorizationUtility.isExperimentPi(user, experiment);
}
public boolean isExperimentUser(Experiment experiment) {
return AuthorizationUtility.isExperimentUser(user, experiment);
}
public boolean canManageStation(ExperimentStation experimentStation) {
return AuthorizationUtility.canManageStation(user, experimentStation);
}
public boolean canManageExperiment(Experiment experiment) {
return AuthorizationUtility.canManageExperiment(user, experiment);
}
public boolean canCreateExperiment() {
return AuthorizationUtility.canCreateExperiment(user);
}
}
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.portal.model.beans.SystemRoleTypeDbFacade;
import gov.anl.aps.dm.portal.model.entities.SystemRoleType;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.apache.log4j.Logger;
@Named("systemRoleTypeController")
@SessionScoped
public class SystemRoleTypeController extends DmEntityController<SystemRoleType, SystemRoleTypeDbFacade> {
private static final Logger logger = Logger.getLogger(SystemRoleTypeController.class.getName());
@EJB
private SystemRoleTypeDbFacade systemRoleTypeDbFacade;
public SystemRoleTypeController() {
}
@Override
protected SystemRoleTypeDbFacade getFacade() {
return systemRoleTypeDbFacade;
}
@Override
protected SystemRoleType createEntityInstance() {
return new SystemRoleType();
}
@Override
public String getEntityTypeName() {
return "systemRoleType";
}
@Override
public String getCurrentEntityInstanceName() {
if (getCurrent() != null) {
return getCurrent().getName();
}
return "";
}
@Override
public SystemRoleType findById(Integer id) {
return systemRoleTypeDbFacade.findById(id);
}
@FacesConverter(forClass = SystemRoleType.class)
public static class SystemRoleTypeControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
SystemRoleTypeController controller = (SystemRoleTypeController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "systemRoleTypeController");
return controller.getEntity(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof SystemRoleType) {
SystemRoleType o = (SystemRoleType) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("Object " + object + " is of type " + object.getClass().getName() + "; expected type: " + SystemRoleType.class.getName());
}
}
}
}
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.api.ExperimentDsApi;
import gov.anl.aps.dm.common.exceptions.InvalidRequest;
import gov.anl.aps.dm.common.exceptions.DmException;
import gov.anl.aps.dm.common.exceptions.ObjectAlreadyExists;
import gov.anl.aps.dm.portal.model.entities.UserInfo;
import gov.anl.aps.dm.portal.model.beans.UserInfoDbFacade;
import gov.anl.aps.dm.common.utilities.CryptUtility;
import gov.anl.aps.dm.portal.model.beans.UserExperimentRoleDbFacade;
import gov.anl.aps.dm.portal.model.beans.ExperimentRoleTypeDbFacade;
import gov.anl.aps.dm.portal.model.entities.Experiment;
import gov.anl.aps.dm.portal.model.entities.ExperimentRoleType;
import gov.anl.aps.dm.portal.model.entities.UserExperimentRole;
import gov.anl.aps.dm.portal.model.entities.UserExperimentRolePK;
import gov.anl.aps.dm.portal.utilities.DmApiFactory;
import gov.anl.aps.dm.portal.utilities.SessionUtility;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.inject.Named;
import org.apache.log4j.Logger;
@Named("userInfoController")
@SessionScoped
public class UserInfoController extends DmEntityController<UserInfo, UserInfoDbFacade> {
private static final Logger logger = Logger.getLogger(UserInfoController.class.getName());
@EJB
private UserInfoDbFacade userInfoDbFacade;
@EJB
private UserExperimentRoleDbFacade userExperimentRoleDbFacade;
@EJB
private ExperimentRoleTypeDbFacade experimentRoleTypeDbFacade;
private String passwordEntry = null;
private UserExperimentRole currentUserExperimentRole = null;
private String filterByBadge = null;
private String filterByUsername = null;
private String filterByLastName = null;
private String filterByFirstName = null;
private String filterByEmail = null;
private String filterByGlobusUsername = null;
private String filterByDescription = null;
private String selectFilterByBadge = null;
private String selectFilterByUsername = null;
private String selectFilterByLastName = null;
private String selectFilterByFirstName = null;
private String selectFilterByEmail = null;
private String selectFilterByGlobusUsername = null;
private String selectFilterByDescription = null;
public UserInfoController() {
}
@Override
protected UserInfoDbFacade getFacade() {
return userInfoDbFacade;
}
@Override
protected UserInfo createEntityInstance() {
return new UserInfo();
}
@Override
public String getEntityTypeName() {
return "user";
}
@Override
public String getCurrentEntityInstanceName() {
if (getCurrent() != null) {
return getCurrent().getUsername();
}
return "";
}
@Override
public UserInfo findById(Integer id) {
return userInfoDbFacade.findById(id);
}
@Override
public List<UserInfo> getAvailableItems() {
return super.getAvailableItems();
}
@Override
public String prepareEdit(UserInfo user) {
passwordEntry = null;
return super.prepareEdit(user);
}
@Override
public void prepareEntityInsert(UserInfo user) throws DmException {
checkMandatoryParameters(user);
UserInfo existingUser = userInfoDbFacade.findByUsername(user.getUsername());
if (existingUser != null) {
throw new ObjectAlreadyExists("User " + user.getUsername() + " already exists.");
}
if (passwordEntry != null && !passwordEntry.isEmpty()) {
logger.debug("Will crypt provided password for user " + user.getUsername());
String cryptedPassword = CryptUtility.cryptPasswordWithPbkdf2(passwordEntry);
user.setPassword(cryptedPassword);
}
passwordEntry = null;
user.setIsLocalUser(true);
logger.debug("Inserting new user " + user.getUsername());
}
private void checkMandatoryParameters(UserInfo user) throws InvalidRequest {
if ((user.getUsername() == null) || (user.getUsername().length() == 0)) {
throw new InvalidRequest("Missing username.");
}
if ((user.getLastName() == null) || (user.getLastName().length() == 0)) {
throw new InvalidRequest("Missing user last name.");
}
if ((user.getFirstName() == null) || (user.getFirstName().length() == 0)) {
throw new InvalidRequest("Missing user first name.");
}
}
@Override
public void prepareEntityUpdate(UserInfo user) throws DmException {
checkMandatoryParameters(user);
if (passwordEntry != null && !passwordEntry.isEmpty()) {
logger.debug("Will crypt provided password for user " + user.getUsername());
String cryptedPassword = CryptUtility.cryptPasswordWithPbkdf2(passwordEntry);
user.setPassword(cryptedPassword);
}
passwordEntry = null;
}
@Override
protected String getObjectAlreadyExistMessage(UserInfo user) {
if (user == null) {
return null;
}
return "User " + user.getUsername() + " already exists.";
}
public String prepareSessionUserEdit(String viewPath) {
UserInfo sessionUser = (UserInfo) SessionUtility.getUser();
if (sessionUser == null) {
return null;
}
prepareEdit(sessionUser);
return viewPath + "?faces-redirect=true";
}
public String getPasswordEntry() {
return passwordEntry;
}
public void setPasswordEntry(String passwordEntry) {
this.passwordEntry = passwordEntry;
}
public UserExperimentRole getCurrentUserExperimentRole() {
if (currentUserExperimentRole == null) {
currentUserExperimentRole = new UserExperimentRole();
}
return currentUserExperimentRole;
}
public void setCurrentUserExperimentRole(UserExperimentRole currentUserExperimentRole) {
this.currentUserExperimentRole = currentUserExperimentRole;
}
public void prepareAddUserExperimentRole(UserInfo user) {
UserExperimentRole userExperimentRole = getCurrentUserExperimentRole();
userExperimentRole.setUserInfo(user);
}
private void addUserExperimentRole() {
UserInfo user = currentUserExperimentRole.getUserInfo();
Experiment experiment = currentUserExperimentRole.getExperiment();
ExperimentRoleType roleType = currentUserExperimentRole.getExperimentRoleType();
UserExperimentRolePK userExperimentRolePK = new UserExperimentRolePK();
userExperimentRolePK.setExperimentId(experiment.getId());
userExperimentRolePK.setUserId(user.getId());
userExperimentRolePK.setRoleTypeId(roleType.getId());
currentUserExperimentRole.setUserExperimentRolePK(userExperimentRolePK);
UserExperimentRole existingRole = userExperimentRoleDbFacade.findByUserAndExperiment(user.getId(),
experiment.getId());
if (existingRole != null) {
SessionUtility.addErrorMessage("Error", "Could not add user experiment role: User "
+ user.getUsername()
+ " is already associated with experiment "
+ existingRole.getExperiment().getName() + " as "
+ existingRole.getExperimentRoleType().getName() + ".");
return;
}
List<UserExperimentRole> userExperimentRoleList = user.getUserExperimentRoleList();
userExperimentRoleList.add(0, currentUserExperimentRole);
update();
notifyUpdateExperiment(experiment);
currentUserExperimentRole = null;
}
public void addUserExperimentRolePi() {
currentUserExperimentRole.setExperimentRoleType(experimentRoleTypeDbFacade.findPiRoleType());
addUserExperimentRole();
}
public void addUserExperimentRoleUser() {
currentUserExperimentRole.setExperimentRoleType(experimentRoleTypeDbFacade.findUserRoleType());
addUserExperimentRole();
}
public void deleteUserExperimentRole(UserExperimentRole userExperimentRole) {
UserInfo user = getCurrent();
userExperimentRoleDbFacade.remove(userExperimentRole);
List<UserExperimentRole> userExperimentRoleList = user.getUserExperimentRoleList();
userExperimentRoleList.remove(userExperimentRole);
updateOnRemoval();
notifyUpdateExperiment(userExperimentRole.getExperiment());
}
public void notifyUpdateExperiment(Experiment experiment) {
// Notify DS Web Service
try {
ExperimentDsApi api = DmApiFactory.getExperimentDsApi();
api.updateExperiment(experiment.getName());
} catch (DmException ex) {
logger.error("Could not notify Data Storage Service: " + ex);
SessionUtility.addErrorMessage("Error", "Unable to notify Data Storage Service: " + ex.getErrorMessage());
}
}
@Override
public void clearListFilters() {
filterByBadge = null;
filterByUsername = null;
filterByLastName = null;
filterByFirstName = null;
filterByEmail = null;
filterByGlobusUsername = null;
filterByDescription = null;
}
@Override
public void clearSelectFilters() {
selectFilterByBadge = null;
selectFilterByUsername = null;
selectFilterByLastName = null;
selectFilterByFirstName = null;
selectFilterByEmail = null;
selectFilterByGlobusUsername = null;
selectFilterByDescription = null;
}
public String getFilterByBadge() {
return filterByBadge;
}
public void setFilterByBadge(String filterByBadge) {
this.filterByBadge = filterByBadge;
}
public String getFilterByUsername() {
return filterByUsername;
}
public void setFilterByUsername(String filterByUsername) {
this.filterByUsername = filterByUsername;
}
public String getFilterByLastName() {
return filterByLastName;
}
public void setFilterByLastName(String filterByLastName) {
this.filterByLastName = filterByLastName;
}
public String getFilterByFirstName() {
return filterByFirstName;
}
public void setFilterByFirstName(String filterByFirstName) {
this.filterByFirstName = filterByFirstName;
}
public String getFilterByEmail() {
return filterByEmail;
}
public void setFilterByEmail(String filterByEmail) {
this.filterByEmail = filterByEmail;
}
public String getFilterByGlobusUsername() {
return filterByGlobusUsername;
}
public void setFilterByGlobusUsername(String filterByGlobusUsername) {
this.filterByGlobusUsername = filterByGlobusUsername;
}
public String getFilterByDescription() {
return filterByDescription;
}
public void setFilterByDescription(String filterByDescription) {
this.filterByDescription = filterByDescription;
}
public String getSelectFilterByBadge() {
return selectFilterByBadge;
}
public void setSelectFilterByBadge(String selectFilterByBadge) {
this.selectFilterByBadge = selectFilterByBadge;
}
public String getSelectFilterByUsername() {
return selectFilterByUsername;
}
public void setSelectFilterByUsername(String selectFilterByUsername) {
this.selectFilterByUsername = selectFilterByUsername;
}
public String getSelectFilterByLastName() {
return selectFilterByLastName;
}
public void setSelectFilterByLastName(String selectFilterByLastName) {
this.selectFilterByLastName = selectFilterByLastName;
}
public String getSelectFilterByFirstName() {
return selectFilterByFirstName;
}
public void setSelectFilterByFirstName(String selectFilterByFirstName) {
this.selectFilterByFirstName = selectFilterByFirstName;
}
public String getSelectFilterByEmail() {
return selectFilterByEmail;
}
public void setSelectFilterByEmail(String selectFilterByEmail) {
this.selectFilterByEmail = selectFilterByEmail;
}
public String getSelectFilterByGlobusUsername() {
return selectFilterByGlobusUsername;
}
public void setSelectFilterByGlobusUsername(String selectFilterByGlobusUsername) {
this.selectFilterByGlobusUsername = selectFilterByGlobusUsername;
}
public String getSelectFilterByDescription() {
return selectFilterByDescription;
}
public void setSelectFilterByDescription(String selectFilterByDescription) {
this.selectFilterByDescription = selectFilterByDescription;
}
@FacesConverter(forClass = UserInfo.class)
public static class UserInfoControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
UserInfoController controller = (UserInfoController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "userInfoController");
return controller.getEntity(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof UserInfo) {
UserInfo o = (UserInfo) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("Object " + object + " is of type " + object.getClass().getName() + "; expected type: " + UserInfo.class.getName());
}
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.anl.aps.dm.portal.model.beans;
import gov.anl.aps.dm.portal.model.entities.AllowedPolicyValue;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
/**
*
* @author sveseli
*/
@Stateless
public class AllowedPolicyValueDbFacade extends DmEntityDbFacade<AllowedPolicyValue>
{
@PersistenceContext(unitName = "DmWebPortalPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public AllowedPolicyValueDbFacade() {
super(AllowedPolicyValue.class);
}
public AllowedPolicyValue findByName(String name) {
try {
return (AllowedPolicyValue) em.createNamedQuery("AllowedPolicyValue.findByPolicyValue")
.setParameter("policyValue", name)
.getSingleResult();
} catch (NoResultException ex) {
}
return null;
}
public AllowedPolicyValue findById(int id) {
try {
return (AllowedPolicyValue) em.createNamedQuery("AllowedPolicyValue.findById")
.setParameter("id", id)
.getSingleResult();
} catch (NoResultException ex) {
}
return null;
}
public List<AllowedPolicyValue> findByPolicyPropertyId(int id) {
try {
return (List<AllowedPolicyValue>) em.createNamedQuery("AllowedPolicyValue.findByPolicyPropertyId")
.setParameter("policyPropertyId", id)
.getResultList();
} catch (NoResultException ex) {
}
return null;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.anl.aps.dm.portal.model.beans;
import gov.anl.aps.dm.portal.model.entities.AllowedSettingValue;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author sveseli
*/
@Stateless
public class AllowedSettingValueDbFacade extends DmEntityDbFacade<AllowedSettingValue>
{
@PersistenceContext(unitName = "DmWebPortalPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public AllowedSettingValueDbFacade() {
super(AllowedSettingValue.class);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.anl.aps.dm.portal.model.beans;
import gov.anl.aps.dm.portal.model.entities.DataFolder;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author sveseli
*/
@Stateless
public class DataFolderDbFacade extends DmEntityDbFacade<DataFolder>
{
@PersistenceContext(unitName = "DmWebPortalPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public DataFolderDbFacade() {
super(DataFolder.class);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.anl.aps.dm.portal.model.beans;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* @author sveseli
*/
public abstract class DmEntityDbFacade<T>
{
private Class<T> entityClass;
public DmEntityDbFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.anl.aps.dm.portal.model.beans;
import gov.anl.aps.dm.portal.model.entities.Endpoint;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author sveseli
*/
@Stateless
public class EndpointDbFacade extends DmEntityDbFacade<Endpoint> {
@PersistenceContext(unitName = "DmWebPortalPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public EndpointDbFacade() {
super(Endpoint.class);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.anl.aps.dm.portal.model.beans;
import gov.anl.aps.dm.portal.model.entities.Experiment;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
/**
*
* @author sveseli
*/
@Stateless
public class ExperimentDbFacade extends DmEntityDbFacade<Experiment> {
@PersistenceContext(unitName = "DmWebPortalPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public ExperimentDbFacade() {
super(Experiment.class);
}
public Experiment findByName(String name) {
try {
return (Experiment) em.createNamedQuery("Experiment.findByName")
.setParameter("name", name)
.getSingleResult();
} catch (NoResultException ex) {
}
return null;
}
public Experiment findById(Integer id) {
try {
return (Experiment) em.createNamedQuery("Experiment.findById")
.setParameter("id", id)
.getSingleResult();
} catch (NoResultException ex) {
}
return null;
}
public boolean checkIfNameExists(String name) {
return findByName(name) != null;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.anl.aps.dm.portal.model.beans;
import gov.anl.aps.dm.portal.model.entities.ExperimentPolicy;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
/**
*
* @author sveseli
*/
@Stateless
public class ExperimentPolicyDbFacade extends DmEntityDbFacade<ExperimentPolicy>
{
@PersistenceContext(unitName = "DmWebPortalPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public ExperimentPolicyDbFacade() {
super(ExperimentPolicy.class);
}
public ExperimentPolicy findById(int id) {
try {
return (ExperimentPolicy) em.createNamedQuery("ExperimentPolicy.findById")
.setParameter("id", id)
.getSingleResult();
}
catch (NoResultException ex) {
}
return null;
}
public List<ExperimentPolicy> findByExperimentId(int id) {
try {
return (List<ExperimentPolicy>) em.createNamedQuery("ExperimentPolicy.findByExperimentId")
.setParameter("experimentId", id)
.getResultList();
}
catch (NoResultException ex) {
}
return null;
}
}