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 1296 additions and 0 deletions
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Communication error exception.
*/
public class CommunicationError extends DmException {
/**
* Default constructor.
*/
public CommunicationError() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public CommunicationError(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public CommunicationError(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public CommunicationError(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_COMMUNICATION_ERROR;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Configuration error exception.
*/
public class ConfigurationError extends DmException {
/**
* Default constructor.
*/
public ConfigurationError() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public ConfigurationError(String message) {
super(message);
}
/**
* Constructor sing throwable object.
*
* @param throwable throwable object
*/
public ConfigurationError(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public ConfigurationError(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_CONFIGURATION_ERROR;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* DB error exception.
*/
public class DbError extends DmException {
/**
* Default constructor.
*/
public DbError() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public DbError(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public DbError(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public DbError(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_DB_ERROR;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Generic DM exception, used as base class for all DM exceptions.
*/
public class DmException extends Exception {
/**
* Exception keys.
*/
public static final String SIGNATURE_KEY = "__dm_exception__";
public static final String TYPE_KEY = "type";
public static final String CODE_KEY = "code";
public static final String ARGS_KEY = "args";
private String error = null;
/**
* Default constructor.
*/
public DmException() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public DmException(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public DmException(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public DmException(String message, Throwable throwable) {
super(message, throwable);
}
public int getErrorCode() {
return DmStatus.DM_ERROR;
}
public void setErrorMessage(String error) {
this.error = error;
}
public String getErrorMessage() {
if (error != null) {
return error;
}
return super.getMessage();
}
/**
* Convert exception to string, overriding string output if error message is
* set.
*
* @return exception string
*/
@Override
public String toString() {
if (error != null) {
return error;
} else {
return super.toString();
}
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
import org.apache.log4j.Logger;
/**
* DM exception factory class.
*
*/
public class DmExceptionFactory {
private static final Logger logger
= Logger.getLogger(DmExceptionFactory.class.getName());
/**
* Generate DM exception.
*
* @param type exception type
* @param code exception code
* @param error exception error message
* @return generated DM exception
*/
public static DmException generateDmException(String type, int code, String error) {
DmException exc = new DmException();
try {
String fullType = "gov.anl.aps.dm.common.exceptions." + type;
// Having trouble getting code below to work in all cases, so
// use code for now.
// exc = (DmException) Class.forName(fullType).newInstance();
switch (code) {
case DmStatus.DM_AUTHORIZATION_ERROR:
exc = new AuthorizationError();
break;
case DmStatus.DM_COMMUNICATION_ERROR:
exc = new CommunicationError();
break;
case DmStatus.DM_CONFIGURATION_ERROR:
exc = new ConfigurationError();
break;
case DmStatus.DM_INTERNAL_ERROR:
exc = new InternalError();
break;
case DmStatus.DM_DB_ERROR:
exc = new DbError();
break;
case DmStatus.DM_INVALID_ARGUMENT:
exc = new InvalidArgument();
break;
case DmStatus.DM_INVALID_REQUEST:
exc = new InvalidRequest();
break;
case DmStatus.DM_INVALID_SESSION:
exc = new InvalidSession();
break;
case DmStatus.DM_OBJECT_ALREADY_EXISTS:
exc = new ObjectAlreadyExists();
break;
case DmStatus.DM_OBJECT_NOT_FOUND:
exc = new ObjectNotFound();
break;
case DmStatus.DM_INVALID_OBJECT_STATE:
exc = new InvalidObjectState();
break;
case DmStatus.DM_TIMEOUT_ERROR:
exc = new TimeoutError();
break;
default:
exc = (DmException) Class.forName(fullType).newInstance();
}
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
String err = "Cannot generate exception of type " + type + ": " + ex;
logger.error(err);
}
exc.setErrorMessage(error);
return exc;
}
/**
* Throw DM exception.
*
* @param type exception type
* @param code exception code
* @param error exception error message
* @throws DmException generated DM exception whenever this method is
* called
*/
public static void throwDmException(String type, int code, String error) throws DmException {
DmException exc = generateDmException(type, code, error);
throw exc;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Internal error exception.
*/
public class InternalError extends DmException {
/**
* Default constructor.
*/
public InternalError() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public InternalError(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public InternalError(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public InternalError(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_INTERNAL_ERROR;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Invalid argument exception.
*/
public class InvalidArgument extends DmException {
/**
* Default constructor.
*/
public InvalidArgument() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public InvalidArgument(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public InvalidArgument(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public InvalidArgument(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_INVALID_ARGUMENT;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Invalid object state exception.
*/
public class InvalidObjectState extends DmException {
/**
* Default constructor.
*/
public InvalidObjectState() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public InvalidObjectState(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public InvalidObjectState(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public InvalidObjectState(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_INVALID_OBJECT_STATE;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Invalid request exception.
*/
public class InvalidRequest extends DmException {
/**
* Default constructor.
*/
public InvalidRequest() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public InvalidRequest(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public InvalidRequest(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public InvalidRequest(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_INVALID_REQUEST;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Invalid session exception.
*/
public class InvalidSession extends DmException {
/**
* Default constructor.
*/
public InvalidSession() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public InvalidSession(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public InvalidSession(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public InvalidSession(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_INVALID_SESSION;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Object already exists exception.
*/
public class ObjectAlreadyExists extends DmException {
/**
* Default constructor.
*/
public ObjectAlreadyExists() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public ObjectAlreadyExists(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public ObjectAlreadyExists(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public ObjectAlreadyExists(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_OBJECT_ALREADY_EXISTS;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Object not found exception.
*/
public class ObjectNotFound extends DmException {
/**
* Default constructor.
*/
public ObjectNotFound() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public ObjectNotFound(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public ObjectNotFound(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public ObjectNotFound(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_OBJECT_NOT_FOUND;
}
}
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());
}
}