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 2267 additions and 0 deletions
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Timeout error.
*/
public class TimeoutError extends DmException {
/**
* Default constructor.
*/
public TimeoutError() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public TimeoutError(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public TimeoutError(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public TimeoutError(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_TIMEOUT_ERROR;
}
}
package gov.anl.aps.dm.common.objects;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import gov.anl.aps.dm.common.exceptions.DmException;
import java.io.Serializable;
/**
* Base DM object class.
*/
public class DmObject implements Serializable {
protected Long id = null;
protected String name = null;
protected String description = null;
public DmObject() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* Conversion to JSON string representation.
*
* @return JSON string
*/
public String toJson() {
Gson gson = new GsonBuilder().create();
return gson.toJson(this);
}
/**
* Encode object.
*
* @throws DmException in case of any errors
*/
public void encode() throws DmException {
}
/**
* Decode object.
*
* @throws DmException in case of any errors
*/
public void decode() throws DmException {
}
}
package gov.anl.aps.dm.common.objects;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import gov.anl.aps.dm.common.exceptions.DmException;
import java.lang.reflect.Type;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* DM object factory class.
*/
public class DmObjectFactory {
private static final Logger logger = Logger.getLogger(DmObjectFactory.class.getName());
private static final Gson gson = new GsonBuilder().create();
/**
* Create object from JSON string.
*
* @param <T> template class
* @param jsonString JSON string
* @param objectClass object class
* @return generated object
*/
public static <T extends Object> T createObject(String jsonString, Class<T> objectClass) {
logger.debug("Converting JSON string to object " + objectClass + ": " + jsonString);
T object = gson.fromJson(jsonString, objectClass);
return object;
}
/**
* Create DM object from JSON string.
*
* @param <T> template class
* @param jsonString JSON string
* @param dmClass DM object class
* @return generated DM object
* @throws DmException in case of any errors
*/
public static <T extends DmObject> T createDmObject(String jsonString, Class<T> dmClass) throws DmException {
logger.debug("Converting JSON string to DM object " + dmClass + ": " + jsonString);
T dmObject = gson.fromJson(jsonString, dmClass);
dmObject.decode();
return dmObject;
}
/**
* Create list of DM objects from JSON string.
*
* @param <T> template class
* @param jsonString DM string
* @return generated list of DM objects
*/
public static <T extends DmObject> List<T> createDmObjectList(String jsonString) {
// This method does not appear to work as template, so we have
// to write specific methods for each object type.
logger.debug("Converting JSON string to dm object list: " + jsonString);
Type dmType = new TypeToken<LinkedList<T>>() {
}.getType();
List<T> dmObjectList = gson.fromJson(jsonString, dmType);
return dmObjectList;
}
/**
* Create list of string objects from JSON string.
*
* @param jsonString JSON string
* @return generated list of string objects
*/
public static List<String> createStringObjectList(String jsonString) {
logger.debug("Converting JSON string to string object list: " + jsonString);
Type dmType = new TypeToken<LinkedList<String>>() {
}.getType();
List<String> dmObjectList = gson.fromJson(jsonString, dmType);
return dmObjectList;
}
}
/*
* 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.common.objects;
/**
* Experiment class.
*/
public class Experiment extends DmObject {
public Experiment() {
}
}
package gov.anl.aps.dm.common.utilities;
import gov.anl.aps.dm.common.exceptions.InvalidArgument;
import gov.anl.aps.dm.common.exceptions.DmException;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
/**
* Utility class for processing and checking function arguments.
*/
public class ArgumentUtility {
/**
* Check that input string is not null and not empty.
*
* @param arg input argument to be checked
* @return true if input string is not null and not empty, false otherwise
*/
public static boolean isNonEmptyString(String arg) {
return arg != null && !arg.isEmpty();
}
/**
* Convert input argument to string.
*
* @param arg input argument to be checked
* @return original argument string representation, or empty string if
* argument is null
*/
public static String toNonNullString(Object arg) {
if (arg == null) {
return "";
}
return arg.toString();
}
/**
* Verify that input string is not null and not empty.
*
* @param argName name of the argument to be verified; used for error
* message
* @param arg input argument to be checked
* @throws InvalidArgument if input string is null or empty
*/
public static void verifyNonEmptyString(String argName, String arg) throws InvalidArgument {
if (arg == null || arg.isEmpty()) {
throw new InvalidArgument(argName + " must be non-empty string.");
}
}
/**
* Verify that input string contains given pattern.
*
* @param argName name of the argument to be verified; used for error
* message
* @param arg input argument to be checked
* @param pattern string that must be contained in the input argument
* @throws InvalidArgument if input string is null or empty, or if it does
* not contain specified pattern
*/
public static void verifyStringContainsPattern(String argName, String arg, String pattern) throws InvalidArgument {
verifyNonEmptyString(argName, arg);
verifyNonEmptyString("Pattern", pattern);
if (!arg.contains(pattern)) {
throw new InvalidArgument(argName + " must contain pattern " + pattern + ".");
}
}
/**
* Verify that input integer is not null and greater than zero.
*
* @param argName name of the argument to be verified; used for error
* message
* @param arg input argument to be checked
* @throws InvalidArgument if input number is null or not positive
*/
public static void verifyPositiveInteger(String argName, Integer arg) throws InvalidArgument {
if (arg == null || arg <= 0) {
throw new InvalidArgument(argName + " must be a positive number.");
}
}
/**
* Verify that input double is not null and greater than zero.
*
* @param argName name of the argument to be verified; used for error
* message
* @param arg input argument to be checked
* @throws InvalidArgument if input number is null or not positive
*/
public static void verifyPositiveDouble(String argName, Double arg) throws InvalidArgument {
if (arg == null || arg <= 0) {
throw new InvalidArgument(argName + " must be a positive number.");
}
}
/**
* Verify that input object is not null.
*
* @param argName name of the argument to be verified; used for error
* message
* @param arg input argument to be checked
* @throws InvalidArgument if input string is null or empty
*/
public static void verifyNonNullObject(String argName, Object arg) throws InvalidArgument {
if (arg == null) {
throw new InvalidArgument(argName + " cannot be null.");
}
}
/**
* Add (key,value) pair to map if value is not null or empty.
*
* @param map target map
* @param key key
* @param value string that will be added to map if it is not null or empty
*/
public static void addNonEmptyKeyValuePair(Map<String, String> map, String key, String value) {
if (value != null && !value.isEmpty()) {
map.put(key, value);
}
}
/**
* Add (key,value) pair to map if value is not null or empty.
*
* @param map target map
* @param key key
* @param valueObject object that will be added to map if it has non-empty
* string representation
*/
public static void addNonEmptyKeyValuePair(Map<String, String> map, String key, Object valueObject) {
if (valueObject != null) {
String value = valueObject.toString();
if (!value.isEmpty()) {
map.put(key, value);
}
}
}
/**
* Base 64 encode.
*
* @param input input string
* @return base 64 encoded string
* @throws DmException in case of any errors
*/
public static String encode(String input) throws DmException {
try {
// Input is twice encoded in order to avoid issues like
// '+' being interpreted as space
if (input == null) {
return input;
}
String s1 = DatatypeConverter.printBase64Binary(input.getBytes());
String s2 = DatatypeConverter.printBase64Binary(s1.getBytes());
return s2;
} catch (Exception ex) {
throw new DmException(ex);
}
}
/**
* Base 64 decode.
*
* @param input base 64 encoded string
* @return decoded string
* @throws DmException in case of any errors
*/
public static String decode(String input) throws DmException {
try {
// Input is twice encoded in order to avoid issues like
// '+' being interpreted as space
byte[] ba1 = DatatypeConverter.parseBase64Binary(input);
byte[] ba2 = DatatypeConverter.parseBase64Binary(new String(ba1));
return new String(ba2);
} catch (Exception ex) {
throw new DmException(ex);
}
}
}
package gov.anl.aps.dm.common.utilities;
import java.util.List;
import java.util.ListIterator;
import javax.faces.model.SelectItem;
/**
* Utility class for manipulating collections.
*/
public class CollectionUtility {
/**
* Prepare array of SelectItem objects for menus
*
* @param entities list of objects
* @param selectOne true if resulting array should contain "Select" string
* @return array of SelectItem objects
*/
public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = selectOne ? entities.size() + 1 : entities.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem("", "Select");
i++;
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
/**
* Prepare display string for a list of objects.
*
* @param list object list
* @param beginDelimiter beginning delimiter
* @param itemDelimiter item delimiter
* @param endDelimiter ending delimiter
* @return list display string
*/
public static String displayItemList(List<?> list, String beginDelimiter, String itemDelimiter, String endDelimiter) {
String result = beginDelimiter;
boolean addItemDelimiter = false;
if (list != null) {
for (Object item : list) {
if (!addItemDelimiter) {
addItemDelimiter = true;
} else {
result += itemDelimiter;
}
result += item.toString();
}
}
result += endDelimiter;
return result;
}
/**
* Prepare display string for a list of objects without outside delimiters.
*
* @param list object list
* @param itemDelimiter item delimiter
* @return list display string
*/
public static String displayItemListWithoutOutsideDelimiters(List<?> list, String itemDelimiter) {
String beginDelimiter = "";
String endDelimiter = "";
return displayItemList(list, beginDelimiter, itemDelimiter, endDelimiter);
}
/**
* Prepare display string for a list of objects with spaces as delimiters.
*
* @param list object list
* @return list display string
*/
public static String displayItemListWithoutDelimiters(List<?> list) {
String beginDelimiter = "";
String itemDelimiter = "";
String endDelimiter = "";
return displayItemList(list, beginDelimiter, itemDelimiter, endDelimiter);
}
/**
* Remove null references from list of objects.
*
* @param list object list
*/
public static void removeNullReferencesFromList(List<?> list) {
if (list == null) {
return;
}
ListIterator iterator = list.listIterator();
while (iterator.hasNext()) {
if (iterator.next() == null) {
iterator.remove();
}
}
}
}
package gov.anl.aps.dm.common.utilities;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Random;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.apache.log4j.Logger;
import org.primefaces.util.Base64;
/**
* Utility class for encrypting and verifying passwords.
*/
public class CryptUtility {
private static final String SecretKeyFactoryType = "PBKDF2WithHmacSHA1";
private static final int Pbkdf2Iterations = 1003;
private static final int Pbkdf2KeyLengthInBits = 192;
private static final int SaltLengthInBytes = 4;
private static final char[] SaltCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
private static final String SaltDelimiter = "$";
private static final Logger logger = Logger.getLogger(CryptUtility.class.getName());
/**
* Generate random string.
*
* @param characterSet set to draw characters from
* @param length string length
* @return generated string
*/
public static String randomString(char[] characterSet, int length) {
Random random = new SecureRandom();
char[] result = new char[length];
for (int i = 0; i < result.length; i++) {
// picks a random index out of character set > random character
int randomCharIndex = random.nextInt(characterSet.length);
result[i] = characterSet[randomCharIndex];
}
return new String(result);
}
/**
* Encrypt password using PBKDF2 key derivation function.
*
* @param password input password
* @return encrypted password
*/
public static String cryptPasswordWithPbkdf2(String password) {
String salt = randomString(SaltCharset, SaltLengthInBytes);
return saltAndCryptPasswordWithPbkdf2(password, salt);
}
/**
* Apply salt string and encrypt password using PBKDF2 standard.
*
* @param password input password
* @param salt salt string
* @return encrypted password
*/
public static String saltAndCryptPasswordWithPbkdf2(String password, String salt) {
char[] passwordChars = password.toCharArray();
byte[] saltBytes = salt.getBytes();
PBEKeySpec spec = new PBEKeySpec(
passwordChars,
saltBytes,
Pbkdf2Iterations,
Pbkdf2KeyLengthInBits
);
SecretKeyFactory key;
try {
key = SecretKeyFactory.getInstance(SecretKeyFactoryType);
byte[] hashedPassword = key.generateSecret(spec).getEncoded();
String encodedPassword = Base64.encodeToString(hashedPassword, true);
return salt + SaltDelimiter + encodedPassword;
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
// Should not happen
logger.error("Password cannot be crypted: " + ex);
}
return null;
}
/**
* Verify encrypted password.
*
* @param password password to be verified
* @param cryptedPassword original encrypted password
* @return true if passwords match, false otherwise
*/
public static boolean verifyPasswordWithPbkdf2(String password, String cryptedPassword) {
int saltEnd = cryptedPassword.indexOf(SaltDelimiter);
String salt = cryptedPassword.substring(0, saltEnd);
return cryptedPassword.equals(saltAndCryptPasswordWithPbkdf2(password, salt));
}
/*
* Main method, used for simple testing.
*
* @param args main arguments
*/
public static void main(String[] args) {
String password = "dm";
System.out.println("Original password: " + password);
String cryptedPassword = cryptPasswordWithPbkdf2(password);
System.out.println("Crypted password: " + cryptedPassword);
System.out.println("Verified: " + verifyPasswordWithPbkdf2(password, cryptedPassword));
}
}
package gov.anl.aps.dm.common.utilities;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Utility class for manipulating dates.
*/
public class DateUtility {
private static final SimpleDateFormat DateTimeFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* Format current date.
*
* @return formatted date string
*/
public static String getCurrentDateTime() {
return DateTimeFormat.format(new Date());
}
}
package gov.anl.aps.dm.common.utilities;
/**
* Utility class for manipulating files.
*/
public class FileUtility {
/**
* Get file extension.
*
* @param fileName file name
* @return file extension
*/
public static String getFileExtension(String fileName) {
String extension = "";
if (fileName != null && !fileName.isEmpty()) {
int extIndex = fileName.lastIndexOf('.');
int dirIndex = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
if (extIndex > dirIndex) {
extension = fileName.substring(extIndex + 1);
}
}
return extension.toLowerCase();
}
}
package gov.anl.aps.dm.common.utilities;
import gov.anl.aps.dm.portal.utilities.ConfigurationUtility;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import org.apache.log4j.Logger;
/**
* LDAP utility class for verifying user credentials.
*
* @see NoServerVerificationSSLSocketFactory
*/
public class LdapUtility {
private static final String LdapUrlPropertyName = "dm.portal.ldapUrl";
private static final String LdapDnStringPropertyName = "dm.portal.ldapDnString";
private static final String ldapUrl = ConfigurationUtility.getPortalProperty(LdapUrlPropertyName);
private static final String ldapDnString = ConfigurationUtility.getPortalProperty(LdapDnStringPropertyName);
private static final Logger logger = Logger.getLogger(LdapUtility.class.getName());
/**
* Validate user credentials.
*
* Use username and password to attempt initial connection and bind with
* LDAP server. Successful connection implies that credentials are accepted.
*
* @param username username
* @param password password
*
* @return true if credentials are valid, false otherwise
*/
public static boolean validateCredentials(String username, String password) {
// dump out immediately if not given password
if (password.isEmpty()) {
return false;
}
boolean validated = false;
Hashtable env = new Hashtable();
String dn = ldapDnString.replace("USERNAME", username);
logger.debug("Authenticating: " + dn);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUrl);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, dn);
env.put(Context.SECURITY_CREDENTIALS, password);
// the below property allows us to circumvent server certificate checks
env.put("java.naming.ldap.factory.socket", "gov.anl.aps.dm.common.utilities.NoServerVerificationSSLSocketFactory");
try {
DirContext ctx = new InitialDirContext(env);
validated = true;
} catch (NamingException ex) {
logger.error(ex);
}
return validated;
}
}
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());
}
}
}
}