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 2696 additions and 0 deletions
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
/*
* 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.constants;
/**
*
* @author bfrosik
*/
public class RoleTypeName {
public static final String ADMIN = "Administrator";
public static final String EXPERIMENT_ADMIN = "Experiment_Administrator";
public static final String MANAGER = "Manager";
public static final String PI = "PI";
public static final String USER = "User";
}
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.portal.exceptions.DmPortalException;
import gov.anl.aps.dm.portal.exceptions.MissingProperty;
import gov.anl.aps.dm.portal.exceptions.ObjectAlreadyExists;
import gov.anl.aps.dm.portal.model.entities.AllowedPolicyValue;
import gov.anl.aps.dm.portal.model.beans.AllowedPolicyValueFacade;
import gov.anl.aps.dm.portal.model.entities.PolicyProperty;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.apache.log4j.Logger;
@Named("allowedPolicyValueController")
@SessionScoped
public class AllowedPolicyValueController extends CrudEntityController<AllowedPolicyValue, AllowedPolicyValueFacade>
{
private static final Logger logger = Logger.getLogger(AllowedPolicyValueController.class.getName());
class ValueCopy {
private final String value;
private final String description;
ValueCopy(String value, String description) {
this.value = value;
this.description = description;
}
boolean isUpdated(AllowedPolicyValue editedAllowedPolicyValue) {
return (!editedAllowedPolicyValue.getPolicyValue().equals(value) || !editedAllowedPolicyValue.getDescription().equals(description));
}
String getValue() {
return value;
}
String getDescription() {
return description;
}
}
@EJB
private AllowedPolicyValueFacade allowedPolicyValueFacade;
private final Map<AllowedPolicyValue, ValueCopy> editMap = new HashMap<>();
class AllowedPolicyValueInfoTable extends DataTableController<AllowedPolicyValue> {
@Override
public String getEntityName() {
return "AllowedPolicyValue";
}
@Override
public List<AllowedPolicyValue> findAll() {
return allowedPolicyValueFacade.findByPolicyPropertyId(getPolicyProperty().getId());
}
@Override
public String getTableName() {
return "allowedPolicyValueInfoTable";
}
}
private AllowedPolicyValueInfoTable allowedPolicyValueInfoTable = new AllowedPolicyValueInfoTable();
private PolicyProperty policyProperty;
private int rows = 25;
public AllowedPolicyValueController() {
}
public AllowedPolicyValueInfoTable getAllowedPolicyValueInfoTable() {
return allowedPolicyValueInfoTable;
}
public void setAllowedPolicyValueInfoTable(AllowedPolicyValueInfoTable allowedPolicyValueInfoTable) {
this.allowedPolicyValueInfoTable = allowedPolicyValueInfoTable;
}
public PolicyProperty getPolicyProperty() {
return policyProperty;
}
public void setPolicyProperty(PolicyProperty policyProperty) {
clear();
this.policyProperty = policyProperty;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
@Override
protected AllowedPolicyValueFacade getFacade() {
return allowedPolicyValueFacade;
}
@Override
public DataModel createListDataModel() {
List<AllowedPolicyValue> allowedValueList = allowedPolicyValueFacade.findByPolicyPropertyId(policyProperty.getId());
for (AllowedPolicyValue allowedPolicyValue : allowedValueList) {
editMap.put(allowedPolicyValue, new ValueCopy(allowedPolicyValue.getPolicyValue(), allowedPolicyValue.getDescription()));
}
return new ListDataModel((List) allowedValueList);
}
@Override
public List<AllowedPolicyValue> getAvailableItems() {
List<AllowedPolicyValue> allowedValueList = allowedPolicyValueFacade.findByPolicyPropertyId(policyProperty.getId());
return (allowedValueList);
}
@Override
protected AllowedPolicyValue createEntityInstance() {
return new AllowedPolicyValue();
}
@Override
public String getEntityTypeName() {
return "AllowedPolicyValue";
}
@Override
public String getCurrentEntityInstanceName() {
if (getCurrent() != null) {
return getCurrent().getPolicyValue();
}
return "";
}
@Override
public String prepareEdit(AllowedPolicyValue allowedPolicyValue) {
super.prepareEdit(allowedPolicyValue);
return "/views/allowedPolicyValue/edit?faces-redirect=true";
}
@Override
public String prepareView(AllowedPolicyValue allowedPolicyValue) {
current = allowedPolicyValue;
super.prepareView(allowedPolicyValue);
return "/views/allowedPolicyValue/view?faces-redirect=true";
}
@Override
public String prepareCreate() {
super.prepareCreate();
return "/views/allowedPolicyValue/create?faces-redirect=true";
}
@Override
public String create() {
AllowedPolicyValue newValue = current;
if (super.create() == null) {
return null;
}
policyProperty.getAllowedPolicyValueList().add(newValue);
allowedPolicyValueInfoTable.resetList();
return null;
}
@Override
public String destroy() {
AllowedPolicyValue propertyValue = current;
super.destroy();
policyProperty.getAllowedPolicyValueList().remove(propertyValue);
clear();
return null;
}
@Override
public void prepareEntityInsert(AllowedPolicyValue allowedPolicyValue) throws ObjectAlreadyExists, MissingProperty {
current.setPolicyProperty(policyProperty);
if ((allowedPolicyValue.getPolicyValue() == null) || (allowedPolicyValue.getPolicyValue().length() == 0)) {
throw new MissingProperty("Policy Value is missing.");
}
List<AllowedPolicyValue> propertyAllowedPolicyValueList = allowedPolicyValueFacade.findByPolicyPropertyId(policyProperty.getId());
for (AllowedPolicyValue policyValue : propertyAllowedPolicyValueList) {
if ((allowedPolicyValue.getPolicyValue().equals(policyValue.getPolicyValue()))) {
throw new ObjectAlreadyExists("allowed policy value " + allowedPolicyValue.getPolicyValue() + " already exists for this property.");
}
}
}
@Override
public void prepareEntityUpdate(AllowedPolicyValue allowedPolicyValue) throws DmPortalException {
if ((allowedPolicyValue.getPolicyValue() == null) || (allowedPolicyValue.getPolicyValue().length() == 0)) {
throw new MissingProperty("Policy Value is missing.");
}
ValueCopy tempValueCopy = editMap.get(allowedPolicyValue);
editMap.remove(allowedPolicyValue);
Collection<ValueCopy> propertyAllowedPolicyValueList = editMap.values();
for (ValueCopy valueCopy : propertyAllowedPolicyValueList) {
if ((valueCopy.getValue().equals(allowedPolicyValue.getPolicyValue()))) {
throw new ObjectAlreadyExists("allowed policy value " + allowedPolicyValue.getPolicyValue() + " already exists for this property.");
}
}
editMap.put(allowedPolicyValue, tempValueCopy);
}
@Override
public String prepareList() {
logger.debug("Preparing list");
resetListDataModel();
return "/views/policyProperty/view?faces-redirect=true";
}
@Override
protected String getObjectAlreadyExistMessage(AllowedPolicyValue entity) {
return null;
}
@Override
public void clear() {
allowedPolicyValueInfoTable.resetList();
resetList();
editMap.clear();
}
@Override
public String update() {
Iterator<AllowedPolicyValue> iterator = getListDataModel().iterator();
while (iterator.hasNext()) {
AllowedPolicyValue editedAllowedPolicyValue = iterator.next();
ValueCopy valueCopy = editMap.get(editedAllowedPolicyValue);
if ((valueCopy != null) && (valueCopy.isUpdated(editedAllowedPolicyValue))) {
current = editedAllowedPolicyValue;
super.update();
}
}
clear();
return null;
}
}
\ No newline at end of file
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.portal.exceptions.DmPortalException;
import gov.anl.aps.dm.portal.model.beans.AbstractFacade;
import gov.anl.aps.dm.portal.model.entities.CloneableEntity;
import gov.anl.aps.dm.common.utilities.CollectionUtility;
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.component.datatable.DataTable;
public abstract class CrudEntityController<EntityType extends CloneableEntity, FacadeType extends AbstractFacade<EntityType>> implements Serializable
{
private static final Logger logger = Logger.getLogger(CrudEntityController.class.getName());
protected EntityType current = null;
private DataModel listDataModel = null;
private DataTable listDataTable = null;
private List<EntityType> filteredObjectList = null;
private DataModel selectDataModel = null;
private DataTable selectDataTable = null;
private List<EntityType> selectedObjectList = null;
public CrudEntityController() {
}
@PostConstruct
public void initialize() {
}
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;
}
public void selectByRequestParams() {
}
public EntityType getSelected() {
if (current == null) {
current = createEntityInstance();
}
return current;
}
public String resetList() {
logger.debug("Resetting list");
return prepareList();
}
public String prepareList() {
logger.debug("Preparing list");
resetListDataModel();
return "list?faces-redirect=true";
}
public DataTable getListDataTable() {
if (listDataTable == null) {
logger.debug("Recreating data table");
listDataTable = new DataTable();
}
return listDataTable;
}
public void setListDataTable(DataTable listDataTable) {
this.listDataTable = listDataTable;
}
public DataTable getSelectDataTable() {
return selectDataTable;
}
public void setSelectDataTable(DataTable selectDataTable) {
this.selectDataTable = selectDataTable;
}
public String prepareView(EntityType entity) {
clear();
logger.debug("Preparing view");
current = entity;
return "view?faces-redirect=true";
}
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 DmPortalException {
}
public String create() {
try {
EntityType newEntity = current;
prepareEntityInsert(current);
getFacade().create(current);
SessionUtility.addInfoMessage("Success", "Created " + getDisplayEntityTypeName() + " " + getCurrentEntityInstanceName() + ".");
resetListDataModel();
current = newEntity;
return prepareList();
}
catch (DmPortalException | 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 DmPortalException {
}
public String update() {
try {
logger.debug("Updating " + getDisplayEntityTypeName() + " " + getCurrentEntityInstanceName());
prepareEntityUpdate(current);
EntityType updatedEntity = getFacade().edit(current);
SessionUtility.addInfoMessage("Success", "Updated " + getDisplayEntityTypeName() + " " + getCurrentEntityInstanceName() + ".");
resetListDataModel();
current = updatedEntity;
return view();
}
catch (DmPortalException 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;
}
}
abstract protected String getObjectAlreadyExistMessage(EntityType entity);
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() {
resetListDataModel();
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;
listDataTable = null;
filteredObjectList = null;
current = null;
}
public void resetSelectDataModel() {
selectDataModel = null;
selectDataTable = 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);
}
}
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.portal.model.entities.CloneableEntity;
import java.io.Serializable;
import java.util.List;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.apache.log4j.Logger;
import org.primefaces.component.datatable.DataTable;
public abstract class DataTableController<EntityType extends CloneableEntity> implements Serializable
{
private static final Logger logger = Logger.getLogger(DataTableController.class.getName());
protected EntityType currentObject = null;
private DataModel listDataModel = null;
private DataTable listDataTable = null;
private List<EntityType> filteredObjectList = null;
private List<EntityType> selectedObjectList = null;
public abstract List<EntityType> findAll();
public abstract String getTableName();
public abstract String getEntityName();
public EntityType getCurrentObject() {
return currentObject;
}
public void setCurrentObject(EntityType current) {
this.currentObject = current;
}
public DataModel createListDataModel() {
return new ListDataModel(findAll());
}
public DataModel getListDataModel() {
if (listDataModel == null) {
listDataModel = createListDataModel();
}
return listDataModel;
}
public void resetList() {
logger.debug("Resetting list"+" "+getTableName());
listDataModel = null;
listDataTable = null;
filteredObjectList = null;
selectedObjectList = null;
currentObject = null;
}
public DataTable getListDataTable() {
if (listDataTable == null) {
logger.debug("Recreating data table"+" "+getTableName());
listDataTable = new DataTable();
}
return listDataTable;
}
public void setListDataTable(DataTable listDataTable) {
this.listDataTable = listDataTable;
}
public List<EntityType> getFilteredObjectList() {
return filteredObjectList;
}
public void setFilteredObjectList(List<EntityType> filteredObjectList) {
this.filteredObjectList = filteredObjectList;
}
public List<EntityType> getFilteredItems() {
return filteredObjectList;
}
public void setFilteredItems(List<EntityType> filteredItems) {
this.filteredObjectList = filteredItems;
}
public void resetFilterList() {
filteredObjectList = null;
}
public List<EntityType> getSelectedObjectList() {
return selectedObjectList;
}
public void setSelectedObjectList(List<EntityType> selectedObjectList) {
this.selectedObjectList = selectedObjectList;
}
}
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.portal.constants.RoleTypeName;
import gov.anl.aps.dm.portal.exceptions.DmPortalException;
import gov.anl.aps.dm.portal.exceptions.ObjectAlreadyExists;
import gov.anl.aps.dm.portal.exceptions.InvalidDate;
import gov.anl.aps.dm.portal.exceptions.MissingProperty;
import gov.anl.aps.dm.portal.model.entities.Experiment;
import gov.anl.aps.dm.portal.model.beans.ExperimentFacade;
import gov.anl.aps.dm.portal.model.beans.ExperimentPolicyFacade;
import gov.anl.aps.dm.portal.model.beans.ExperimentPolicyPropertyValueFacade;
import gov.anl.aps.dm.portal.model.beans.PolicyTypeFacade;
import gov.anl.aps.dm.portal.model.beans.RoleTypeFacade;
import gov.anl.aps.dm.portal.model.beans.UserExperimentRoleFacade;
import gov.anl.aps.dm.portal.model.beans.UserInfoFacade;
import gov.anl.aps.dm.portal.model.entities.CloneableEntity;
import gov.anl.aps.dm.portal.model.entities.ExperimentPolicy;
import gov.anl.aps.dm.portal.model.entities.ExperimentPolicyPropertyValue;
import gov.anl.aps.dm.portal.model.entities.PolicyProperty;
import gov.anl.aps.dm.portal.model.entities.PolicyType;
import gov.anl.aps.dm.portal.model.entities.RoleType;
import gov.anl.aps.dm.portal.model.entities.UserExperimentRole;
import gov.anl.aps.dm.portal.model.entities.UserInfo;
import gov.anl.aps.dm.common.utilities.CollectionUtility;
import gov.anl.aps.dm.portal.utilities.DmApiFactory;
import gov.anl.aps.dm.portal.utilities.SessionUtility;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
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 javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
@Named("experimentController")
@SessionScoped
public class ExperimentController extends CrudEntityController<Experiment, ExperimentFacade>
{
private static final Logger logger = Logger.getLogger(ExperimentController.class.getName());
@EJB
private ExperimentFacade experimentFacade;
@EJB
private UserInfoFacade userInfoFacade;
@EJB
private RoleTypeFacade roleTypeFacade;
@EJB
private UserExperimentRoleFacade userExperimentRoleFacade;
@EJB
private PolicyTypeFacade policyTypeFacade;
@EJB
private ExperimentPolicyFacade experimentPolicyFacade;
@EJB
private ExperimentPolicyPropertyValueFacade experimentPolicyPropertyValueFacade;
public class ExperimentUser extends CloneableEntity {
String name;
int experimentId;
private final UserInfo user;
private final boolean[] userRoles;
public ExperimentUser(int experimentId, UserInfo user) {
userRoles = new boolean[maxExperimentRoleTypeId + 1];
this.experimentId = experimentId;
this.user = user;
}
public String getBadge() {
return user.getBadge();
}
public UserInfo getUser() {
return user;
}
public String getGlobusUsername() {
return user.getGlobusUsername();
}
public String getUsername() {
return user.getUsername();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isIsManager() {
return userRoles[experimentRoles.get(RoleTypeName.MANAGER).getId()];
}
public void setIsManager(boolean isManager) {
userRoles[experimentRoles.get(RoleTypeName.MANAGER).getId()] = isManager;
}
public boolean isIsPI() {
return userRoles[experimentRoles.get(RoleTypeName.PI).getId()];
}
public void setIsPI(boolean isPI) {
userRoles[experimentRoles.get(RoleTypeName.PI).getId()] = isPI;
}
public boolean isIsUser() {
return userRoles[experimentRoles.get(RoleTypeName.USER).getId()];
}
public void setIsUser(boolean isUser) {
userRoles[experimentRoles.get(RoleTypeName.USER).getId()] = isUser;
}
public void setIsInRole(RoleType role, boolean isInRole) {
userRoles[role.getId()] = isInRole;
}
public boolean[] getRoles() {
return userRoles;
}
@Override
public int hashCode() {
return user.getId() + experimentId * 100;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ExperimentUser)) {
return false;
}
return ((user.getId() == ((ExperimentUser) object).user.getId()) && (experimentId == ((ExperimentUser) object).experimentId));
}
}
@SessionScoped
class ExperimentUsersTable extends DataTableController<ExperimentUser> {
@Override
public String getEntityName() {
return "ExperimentUser";
}
@Override
public List<ExperimentUser> findAll() {
List<UserInfo> list = userInfoFacade.findUsersInExperiment(getCurrent().getId());
return convertExperimentUsers(list);
}
List<ExperimentUser> convertExperimentUsers(List<UserInfo> list) {
if (!initialized) {
initializeTables();
}
logger.debug("converting ExperimentUser ");
ExperimentUser experimentUser;
for (UserInfo user : list) {
if ((experimentUser = experimentUsers.get(user)) == null) {
experimentUser = new ExperimentUser(getCurrent().getId(), user);
experimentUser.setName(user.getLastName() + ", " + user.getFirstName());
experimentUsers.put(user, experimentUser);
}
for (RoleType roleType : experimentRoles.values()) {
boolean inRole = (user.getExperimentRole(roleType.getId(), getCurrent().getId()) != null);
experimentUser.setIsInRole(roleType, inRole);
}
}
return new ArrayList<>(experimentUsers.values());
}
@Override
public String getTableName() {
return "experimentUsersTable";
}
}
@SessionScoped
class NoExperimentUsersTypeTable extends DataTableController<UserInfo> {
@Override
public String getEntityName() {
return "UserInfo";
}
@Override
public List<UserInfo> findAll() {
resetList();
return userInfoFacade.findNoUsersInExperiment(getCurrent().getId());
}
@Override
public String getTableName() {
return "noExperimentUsersTable";
}
}
@SessionScoped
class ExperimentPolicyTable extends DataTableController<ExperimentPolicy> {
boolean forEdit;
ExperimentPolicyTable(boolean forEdit) {
this.forEdit = forEdit;
}
@Override
public String getEntityName() {
return "ExperimentPolicy";
}
@Override
public List<ExperimentPolicy> findAll() {
resetList();
List<ExperimentPolicy> experimentPolicies = experimentPolicyFacade.findByExperimentId(current.getId());
if (forEdit) {
experimentPropertiesMap.clear();
for (ExperimentPolicy experimentPolicy : experimentPolicies) {
for (ExperimentPolicyPropertyValue experimentPolicyPropertyValue : experimentPolicy.getExperimentPolicyPropertyValueList()) {
experimentPropertiesMap.put(experimentPolicyPropertyValue.getId(), experimentPolicyPropertyValue.getPolicyPropertyValue());
}
}
}
return experimentPolicies;
}
@Override
public String getTableName() {
return "experimentPolicyTable";
}
}
public class PolicyPropertyValue extends CloneableEntity {
private PolicyProperty policyProperty;
private String value;
public PolicyProperty getPolicyProperty() {
return policyProperty;
}
public void setPolicyProperty(PolicyProperty policyProperty) {
this.policyProperty = policyProperty;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public boolean hasAllowedValues() {
return (policyProperty.getAllowedPolicyValueList() != null) && (policyProperty.getAllowedPolicyValueList().size() > 0);
}
public int getId() {
return policyProperty.getId();
}
}
public class MissingPolicyType extends CloneableEntity {
private List<PolicyPropertyValue> noPropertyList = new ArrayList<>();
private final int id;
private final String name;
MissingPolicyType(int id, String name) {
this.id = id;
this.name = name;
}
public List<PolicyPropertyValue> getNoPropertyList() {
return noPropertyList;
}
public void setNoPropertyList(List<PolicyPropertyValue> noPropertyList) {
this.noPropertyList = noPropertyList;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
protected void clear() {
noPropertyList.clear();
}
protected boolean isEmpty() {
return noPropertyList.isEmpty();
}
}
@SessionScoped
public class NoPolicyValueTable extends DataTableController<PolicyPropertyValue> {
NoPolicyValueTable() {
}
@Override
public String getEntityName() {
return "PolicyPropertyValue";
}
@Override
public List<PolicyPropertyValue> findAll() {
setMissingProperties(experimentPolicyFacade.findByExperimentId(current.getId()), policyTypeFacade.findAll());
List<PolicyPropertyValue> missingProperties = new ArrayList<>();
for (MissingPolicyType missingPolicyType : missingPolicyTypes) {
missingProperties.addAll(missingPolicyType.getNoPropertyList());
}
return missingProperties;
}
@Override
public String getTableName() {
return "noPolicyValueTable";
}
}
private final int rows = 25;
private ExperimentPolicyPropertyValue experimentPropertyToDelete;
private ExperimentController.ExperimentUsersTable experimentUsersListTable = new ExperimentController.ExperimentUsersTable();
private ExperimentController.ExperimentUsersTable experimentUsersEditTable = new ExperimentController.ExperimentUsersTable();
private ExperimentController.NoExperimentUsersTypeTable noExperimentUsersTypeTable = new ExperimentController.NoExperimentUsersTypeTable();
private ExperimentController.ExperimentPolicyTable experimentPolicyListTable = new ExperimentController.ExperimentPolicyTable(false);
private ExperimentController.ExperimentPolicyTable experimentPolicyEditTable = new ExperimentController.ExperimentPolicyTable(true);
private ExperimentController.NoPolicyValueTable noPolicyValueTable = new ExperimentController.NoPolicyValueTable();
final private Map<UserInfo, ExperimentUser> experimentUsers = new HashMap<>();
final private Map<String, RoleType> experimentRoles = new HashMap<>();
int maxExperimentRoleTypeId = 0;
boolean initialized = false;
private List<MissingPolicyType> missingPolicyTypes = new ArrayList<>();
private final Map<Integer, String> experimentPropertiesMap = new HashMap<>();
private final List<String> notEditableTypes = new ArrayList<>();
{ notEditableTypes.add("ESAF"); }
public ExperimentController() {
}
@Override
public void clear() {
experimentUsersListTable.resetList();
experimentUsersEditTable.resetList();
experimentUsers.clear();
noExperimentUsersTypeTable.resetList();
experimentPolicyListTable.resetList();
missingPolicyTypes.clear();
experimentPolicyEditTable.resetList();
noPolicyValueTable.resetList();
experimentPropertyToDelete = null;
}
@Override
protected ExperimentFacade getFacade() {
return experimentFacade;
}
@Override
protected Experiment createEntityInstance() {
Experiment newExperiment = new Experiment();
if (!initialized) {
initializeTables();
}
return newExperiment;
}
@Override
public String getEntityTypeName() {
return "experiment";
}
@Override
public String getCurrentEntityInstanceName() {
if (getCurrent() != null) {
return getCurrent().getName();
}
return "";
}
private boolean isAdmin(String username) {
return roleTypeFacade.findByName(RoleTypeName.ADMIN).isAdmin(username);
}
@Override
public DataModel createListDataModel() {
UserInfo logged = (UserInfo) SessionUtility.getUser();
if (logged == null) {
return null;
}
if (isAdmin(logged.getUsername())) {
return new ListDataModel(getFacade().findAll());
} else {
return new ListDataModel(userInfoFacade.findExperimentsInUser(logged.getId()));
}
}
@Override
public List<Experiment> getAvailableItems() {
UserInfo logged = (UserInfo) SessionUtility.getUser();
if (logged == null) {
return null;
}
if (isAdmin(logged.getUsername())) {
return getFacade().findAll();
} else {
return userInfoFacade.findExperimentsInUser(logged.getId());
}
}
@Override
public DataModel createSelectDataModel() {
UserInfo logged = (UserInfo) SessionUtility.getUser();
if (logged == null) {
return null;
}
List<Experiment> selectEntityList;
if (isAdmin(logged.getUsername())) {
selectEntityList = getFacade().findAll();
} else {
selectEntityList = userInfoFacade.findExperimentsInUser(logged.getId());
}
prepareEntityListForSelection(selectEntityList);
return new ListDataModel(selectEntityList);
}
@Override
public SelectItem[] getAvailableItemsForSelectMany() {
UserInfo logged = (UserInfo) SessionUtility.getUser();
if (logged == null) {
return null;
}
if (isAdmin(logged.getUsername())) {
return CollectionUtility.getSelectItems(getFacade().findAll(), false);
} else {
return CollectionUtility.getSelectItems(userInfoFacade.findExperimentsInUser(logged.getId()), false);
}
}
@Override
public SelectItem[] getAvailableItemsForSelectOne() {
UserInfo logged = (UserInfo) SessionUtility.getUser();
if (logged == null) {
return null;
}
if (isAdmin(logged.getUsername())) {
return CollectionUtility.getSelectItems(getFacade().findAll(), true);
} else {
return CollectionUtility.getSelectItems(userInfoFacade.findExperimentsInUser(logged.getId()), true);
}
}
@Override
public String prepareEdit(Experiment experiment) {
clear();
if (!initialized) {
initializeTables();
}
return super.prepareEdit(experiment);
}
private void initializeTables() {
List<RoleType> roleTypesList = roleTypeFacade.findAll();
for (RoleType roleType : roleTypesList) {
if (!roleType.isIsSystemRole()) {
experimentRoles.put(roleType.getName(), roleType);
if (roleType.getId() > maxExperimentRoleTypeId) {
maxExperimentRoleTypeId = roleType.getId();
}
}
}
initialized = true;
}
@Override
public void prepareEntityInsert(Experiment experiment) throws ObjectAlreadyExists, InvalidDate, MissingProperty {
if ((experiment.getName() == null) || (experiment.getName().length() == 0)){
throw new MissingProperty("Experiment name is missing.");
}
Experiment existingExperiment = experimentFacade.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 DmPortalException {
if ((experiment.getName() == null) || (experiment.getName().length() == 0)) {
throw new MissingProperty("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 InvalidDate, MissingProperty {
if (experiment.getExperimentType() == null) {
throw new MissingProperty("Experiment Type is missing.");
}
if ((experiment.getStartDate() != null) && (experiment.getEndDate() != null) && (experiment.getEndDate().before(experiment.getStartDate()))) {
throw new InvalidDate("Experiment end date is before start date.");
}
}
@Override
public String update() {
boolean updated;
for (UserInfo user : experimentUsers.keySet()) {
updated = false;
ExperimentUser experimentUser = experimentUsers.get(user);
for (RoleType roleType : experimentRoles.values()) {
if (!roleType.isIsSystemRole()) {
int roleId = roleType.getId();
if (user.getExperimentRole(roleId, experimentUser.experimentId) == null) {
if (experimentUser.userRoles[roleId]) {
UserExperimentRole userExperimentRole = new UserExperimentRole(user.getId(), experimentUser.experimentId, roleId);
user.addUserExperimentRole(userExperimentRole);
updated = true;
logger.debug("adding userExperimentRole " + user.getId() + " " + experimentUser.experimentId + " " + roleId);
}
} else if (!experimentUser.userRoles[roleId]) {
user.removeExperimentRole(roleId, experimentUser.experimentId);
updated = true;
logger.debug("adding userExperimentRole " + user.getId() + " " + experimentUser.experimentId + " " + roleId);
}
}
if (updated) {
userInfoFacade.edit(user);
}
}
}
Iterator<ExperimentPolicy> iterator = experimentPolicyEditTable.getListDataModel().iterator();
while (iterator.hasNext()) {
ExperimentPolicy experimentPolicy = iterator.next();
for (ExperimentPolicyPropertyValue experimentPolicyPropertyValue : experimentPolicy.getExperimentPolicyPropertyValueList()) {
String oldValue = experimentPropertiesMap.get(experimentPolicyPropertyValue.getId());
String newValue = experimentPolicyPropertyValue.getPolicyPropertyValue();
if ((oldValue != null) && !oldValue.equals(experimentPolicyPropertyValue.getPolicyPropertyValue())) {
experimentPolicyPropertyValue.setModifiedBy(((UserInfo) SessionUtility.getUser()).getUsername());
experimentPolicyPropertyValue.setModifiedDate(new Date());
experimentPolicyPropertyValue.setPolicyPropertyValue(newValue);
experimentPolicyPropertyValueFacade.edit(experimentPolicyPropertyValue);
}
}
}
// 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();
}
void setMissingProperties(List<ExperimentPolicy> experimentPolicies, List<PolicyType> policyTypes) {
for (PolicyType policyType : policyTypes) {
ExperimentPolicy theExperimentPolicy = null;
boolean missingProperties = true;
for (ExperimentPolicy experimentPolicy : experimentPolicies) {
if (experimentPolicy.getPolicyType().getId() == policyType.getId()) {
theExperimentPolicy = experimentPolicy;
if (theExperimentPolicy.getExperimentPolicyPropertyValueList().size() == policyType.getPolicyPropertyList().size()) {
missingProperties = false;
}
break;
}
}
if (missingProperties) {
MissingPolicyType missingPolicyType = new MissingPolicyType(policyType.getId(), policyType.getName());
missingPolicyTypes.add(missingPolicyType);
for (PolicyProperty policyProperty : policyType.getPolicyPropertyList()) {
if ((theExperimentPolicy == null) || (!hasProperty(theExperimentPolicy, policyProperty))) {
PolicyPropertyValue policyPropertyValue = new PolicyPropertyValue();
policyPropertyValue.policyProperty = policyProperty;
policyPropertyValue.value = policyProperty.getDefaultValue();
missingPolicyType.getNoPropertyList().add(policyPropertyValue);
}
}
}
}
}
private boolean hasProperty(ExperimentPolicy experimentPolicy, PolicyProperty policyProperty) {
for (ExperimentPolicyPropertyValue experimentPolicyPropertyValue : experimentPolicy.getExperimentPolicyPropertyValueList()) {
if (experimentPolicyPropertyValue.getPolicyProperty().equals(policyProperty)) {
return true;
}
}
return false;
}
public void updateRemovedExperimentRoles() {
UserExperimentRole userExperimentRole;
for (UserInfo user : experimentUsers.keySet()) {
ExperimentUser experimentUser = experimentUsers.get(user);
for (RoleType roleType : experimentRoles.values()) {
int roleId = roleType.getId();
userExperimentRole = user.getExperimentRole(roleId, experimentUser.experimentId);
if ((userExperimentRole != null ) && (!experimentUser.userRoles[roleId]) ) {
userExperimentRoleFacade.remove(userExperimentRole);
}
}
}
}
public String getRemovedUserName() {
if (experimentUsersEditTable.getCurrentObject() != null) {
return experimentUsersEditTable.getCurrentObject().getUsername();
}
return "";
}
public String getRemovedPolicyName() {
if (experimentPropertyToDelete != null) {
return experimentPropertyToDelete.getPolicyProperty().getName();
}
return "";
}
public void removeUserRoles() {
ExperimentUser experimentUser = experimentUsersEditTable.getCurrentObject();
UserInfo user = experimentUser.getUser();
List<UserExperimentRole> roleList = user.getUserExperimentRoles(experimentUser.experimentId);
for (UserExperimentRole userExperimentRole : roleList) {
userExperimentRoleFacade.remove(userExperimentRole);
}
}
public String removeUser() {
ExperimentUser experimentUser = experimentUsersEditTable.getCurrentObject();
UserInfo user = experimentUser.getUser();
for (RoleType roleType : experimentRoles.values()) {
int roleId = roleType.getId();
if (experimentUser.userRoles[roleId]) {
user.removeExperimentRole(roleId, experimentUser.experimentId);
}
}
userInfoFacade.edit(user);
experimentUsersListTable.resetList();
experimentUsersEditTable.resetList();
experimentUsers.clear();
noExperimentUsersTypeTable.resetList();
return "edit?faces-redirect=true";
}
public void removePolicy() {
experimentPolicyPropertyValueFacade.remove(experimentPropertyToDelete);
}
public String updateRemovedExperimentPolicy() {
ExperimentPolicy experimentPolicy = experimentPropertyToDelete.getExperimentPolicy();
experimentPropertiesMap.remove(experimentPropertyToDelete.getId());
experimentPolicy.getExperimentPolicyPropertyValueList().remove(experimentPropertyToDelete);
experimentPolicyFacade.edit(experimentPolicy);
current = experimentFacade.find(current.getId());
experimentPolicyListTable.resetList();
missingPolicyTypes.clear();
experimentPolicyEditTable.resetList();
noPolicyValueTable.resetList();
return "edit?faces-redirect=true";
}
public String addExperimentUser() {
List<UserInfo> newUsers = noExperimentUsersTypeTable.getSelectedObjectList();
if (newUsers == null) {
logger.debug("null selected list");
return null;
} else if (newUsers.isEmpty()) {
logger.debug("empty selected list");
return null;
} else {
try {
UserExperimentRole userExperimentRole;
for (UserInfo user : newUsers) {
userExperimentRole = new UserExperimentRole(user.getId(), current.getId(), experimentRoles.get(RoleTypeName.USER).getId()); // set the User
user.getUserExperimentRoleList().add(userExperimentRole);
userInfoFacade.edit(user);
}
experimentUsersListTable.resetList();
experimentUsersEditTable.resetList();
experimentUsers.clear();
noExperimentUsersTypeTable.resetList();
return "edit?faces-redirect=true";
} catch (RuntimeException ex) {
SessionUtility.addErrorMessage("Error", "Could not update UserInfo" + ": " + ex.getMessage());
return null;
}
}
}
public String addExperimentPolicyPropertyValues() {
List<PolicyPropertyValue> newProperties = noPolicyValueTable.getSelectedObjectList();
if (newProperties == null) {
logger.debug("null selected list");
return null;
} else if (newProperties.isEmpty()) {
logger.debug("empty selected list");
return null;
} else {
try {
ExperimentPolicyPropertyValue experimentPolicyPropertyValue;
for (PolicyPropertyValue property : newProperties) {
PolicyProperty policyProperty = property.getPolicyProperty();
experimentPolicyPropertyValue = new ExperimentPolicyPropertyValue();
experimentPolicyPropertyValue.setPolicyProperty(policyProperty);
experimentPolicyPropertyValue.setPolicyPropertyValue(property.getValue());
experimentPolicyPropertyValue.setModifiedBy(((UserInfo) SessionUtility.getUser()).getUsername());
experimentPolicyPropertyValue.setModifiedDate(new Date());
ExperimentPolicy experimentPolicy = getOrCreateExperimentPolicy(policyProperty.getPolicyType());
experimentPolicyPropertyValue.setExperimentPolicy(experimentPolicy);
experimentPolicy.getExperimentPolicyPropertyValueList().add(experimentPolicyPropertyValue);
}
super.update();
current = experimentFacade.find(current.getId());
experimentPolicyListTable.resetList();
missingPolicyTypes.clear();
experimentPolicyEditTable.resetList();
noPolicyValueTable.resetList();
return "edit?faces-redirect=true";
} catch (RuntimeException ex) {
SessionUtility.addErrorMessage("Error", "Could not update Experiment Policy" + ": " + ex.getMessage());
return null;
}
}
}
private ExperimentPolicy getOrCreateExperimentPolicy(PolicyType policyType) {
List<ExperimentPolicy> experimentPolicyList = current.getExperimentPolicyList();
for (ExperimentPolicy experimentPolicy: experimentPolicyList) {
if (experimentPolicy.getPolicyType().equals(policyType)) {
return experimentPolicy;
}
}
ExperimentPolicy newExperimentPolicy = new ExperimentPolicy();
newExperimentPolicy.setExperiment(current);
newExperimentPolicy.setPolicyType(policyType);
experimentPolicyList.add(newExperimentPolicy);
policyType.getExperimentPolicyList().add(newExperimentPolicy);
experimentPolicyFacade.create(newExperimentPolicy);
return newExperimentPolicy;
}
public boolean canEditExperiment(Experiment experiment) {
UserInfo logged = (UserInfo) SessionUtility.getUser();
if (logged == null) {
return false;
}
if (experiment == null) {
return false;
}
if (!initialized) {
initializeTables();
}
// user that is Manager or PI can edit experiment
int managerRoleId = experimentRoles.get(RoleTypeName.MANAGER).getId();
int piRoleId = experimentRoles.get(RoleTypeName.PI).getId();
return (logged.getExperimentRole(managerRoleId, experiment.getId()) != null) || (logged.getExperimentRole(piRoleId, experiment.getId()) != null);
}
public boolean isRestricted() {
UserInfo logged = (UserInfo) SessionUtility.getUser();
if (logged == null) {
return false;
}
if (current == null) {
return true;
}
int managerRoleId = experimentRoles.get(RoleTypeName.MANAGER).getId();
int piRoleId = experimentRoles.get(RoleTypeName.PI).getId();
return (logged.getExperimentRole(managerRoleId, current.getId()) == null) && (logged.getExperimentRole(piRoleId, current.getId()) == null);
}
public boolean canDeleteExperiment(Experiment experiment) {
UserInfo logged = (UserInfo) SessionUtility.getUser();
if (logged == null) {
return false;
}
if (experiment == null) {
return false;
}
if (!initialized) {
initializeTables();
}
int managerRoleId = experimentRoles.get(RoleTypeName.MANAGER).getId();
return logged.getExperimentRole(managerRoleId, experiment.getId()) != null;
}
public boolean canAddManager() {
ExperimentUser logged = experimentUsers.get((UserInfo) SessionUtility.getUser());
if (logged == null) {
return false;
}
return logged.isIsManager();
}
public boolean canAddPiAndUser() {
ExperimentUser logged = experimentUsers.get((UserInfo) SessionUtility.getUser());
if (logged == null) {
return false;
}
return logged.isIsManager() || logged.isIsPI();
}
public boolean notSelected() {
return (current == null);
}
public int getRows() {
return rows;
}
public ExperimentController.ExperimentUsersTable getExperimentUsersListTable() {
return experimentUsersListTable;
}
public void setExperimentUsersListTable(ExperimentController.ExperimentUsersTable experimentUsersTable) {
this.experimentUsersListTable = experimentUsersTable;
}
public ExperimentController.ExperimentUsersTable getExperimentUsersEditTable() {
return experimentUsersEditTable;
}
public void setExperimentUsersEditTable(ExperimentController.ExperimentUsersTable experimentUsersTable) {
this.experimentUsersEditTable = experimentUsersTable;
}
public ExperimentController.NoExperimentUsersTypeTable getNoExperimentUsersTypeTable() {
return noExperimentUsersTypeTable;
}
public void setNoExperimentUsersTypeTable(ExperimentController.NoExperimentUsersTypeTable noExperimentUsersTypeTable) {
this.noExperimentUsersTypeTable = noExperimentUsersTypeTable;
}
public ExperimentPolicyTable getExperimentPolicyListTable() {
return experimentPolicyListTable;
}
public void setExperimentPolicyListTable(ExperimentPolicyTable experimentPolicyTable) {
this.experimentPolicyListTable = experimentPolicyTable;
}
public ExperimentPolicyTable getExperimentPolicyEditTable() {
return experimentPolicyEditTable;
}
public void setExperimentPolicyEditTable(ExperimentPolicyTable experimentPolicyEditTable) {
this.experimentPolicyEditTable = experimentPolicyEditTable;
}
public NoPolicyValueTable getNoPolicyValueTable() {
return noPolicyValueTable;
}
public void setNoPolicyValueTable(NoPolicyValueTable noPolicyValueTable) {
this.noPolicyValueTable = noPolicyValueTable;
}
public List<MissingPolicyType> getMissingPolicyTypes() {
return missingPolicyTypes;
}
public void setMissingPolicyTypes(List<MissingPolicyType> missingPolicyTypes) {
this.missingPolicyTypes = missingPolicyTypes;
}
public ExperimentPolicyPropertyValue getExperimentPropertyToDelete() {
return experimentPropertyToDelete;
}
public void setExperimentPropertyToDelete(ExperimentPolicyPropertyValue experimentPropertyToDelete) {
this.experimentPropertyToDelete = experimentPropertyToDelete;
}
public boolean isEditable() {
return notEditableTypes.contains(current.getExperimentType().getName());
}
@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());
}
}
}
}
\ No newline at end of file
package gov.anl.aps.dm.portal.controllers;
import gov.anl.aps.dm.portal.exceptions.DmPortalException;
import gov.anl.aps.dm.portal.exceptions.MissingProperty;
import gov.anl.aps.dm.portal.exceptions.ObjectAlreadyExists;
import gov.anl.aps.dm.portal.model.entities.ExperimentPolicy;
import gov.anl.aps.dm.portal.model.beans.ExperimentPolicyFacade;
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("experimentPolicyController")
@SessionScoped
public class ExperimentPolicyController extends CrudEntityController<ExperimentPolicy, ExperimentPolicyFacade>
{
private static final Logger logger = Logger.getLogger(ExperimentPolicyController.class.getName());
@EJB
private ExperimentPolicyFacade experimentPolicyFacade;
public ExperimentPolicyController() {
}
@Override
protected ExperimentPolicyFacade getFacade() {
return experimentPolicyFacade;
}
@Override
protected ExperimentPolicy createEntityInstance() {
return new ExperimentPolicy();
}
@Override
public String getEntityTypeName() {
return "experimentPolicy";
}
@Override
public String getCurrentEntityInstanceName() {
return "";
}
@Override
public List<ExperimentPolicy> getAvailableItems() {
return super.getAvailableItems();
}
@Override
public String prepareEdit(ExperimentPolicy experimentPolicy) {
return super.prepareEdit(experimentPolicy);
}
@Override
public void prepareEntityInsert(ExperimentPolicy experimentPolicy) throws ObjectAlreadyExists, MissingProperty {
logger.debug("Inserting new experiment policy ");
}
@Override
public void prepareEntityUpdate(ExperimentPolicy experimentPolicy) throws DmPortalException {
}
@Override
protected String getObjectAlreadyExistMessage(ExperimentPolicy experimentPolicy) {
if (experimentPolicy == null) {
return null;
}
return "Experiment Policy " + " already exists.";
}
@FacesConverter(forClass = ExperimentPolicy.class)
public static class ExperimentPolicyControllerConverter implements Converter
{
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ExperimentPolicyController controller = (ExperimentPolicyController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "experimentPolicyController");
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 ExperimentPolicy) {
ExperimentPolicy o = (ExperimentPolicy) object;
return getStringKey(o.getId());
}
else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ExperimentPolicy.class.getName());
}
}
}
}
\ No newline at end of file