No longer using underscores for private variables.
/**
* Operation name.
*/
- private String _name;
+ private String name;
/**
* Constructs an all operation.
*
*/
public AllOperation() {
- _name = OPERATION;
+ name = OPERATION;
}
/**
* @param aName Name of the operation. This name must be unique among all operations.
*/
protected AllOperation(String aName) {
- _name = aName;
+ name = aName;
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.Operation#getName()
*/
public String getName() {
- return _name;
+ return name;
}
}
*/
public class AuthorizationException extends RuntimeException {
- private Object _resource;
- private Operation _operation;
+ private Object resource;
+ private Operation operation;
public AuthorizationException(Object aResource, Operation aOperation) {
super("Operation '" + aOperation + "' not allowed on '" + aResource + "'");
- _resource = aResource;
- _operation = aOperation;
+ resource = aResource;
+ operation = aOperation;
}
public Object getResource() {
- return _resource;
+ return resource;
}
public Operation getOperation() {
- return _operation;
+ return operation;
}
}
/**
* List of ordered authorization rules.
*/
- private List<AuthorizationRule> _rules;
+ private List<AuthorizationRule> rules;
/**
* User accessor used to obtain the current user.
*/
- private UserAccessor _userAccessor;
+ private UserAccessor userAccessor;
/**
* Name for this instance of the authorization service.
*/
- private String _name;
+ private String name;
/**
* Constructs the service.
* @param aName Name of this instance of the service.
*/
public DefaultAuthorizationService(UserAccessor aAccessor, String aName) {
- _rules = new ArrayList<AuthorizationRule>();
- _userAccessor = aAccessor;
- _name = aName;
+ rules = new ArrayList<AuthorizationRule>();
+ userAccessor = aAccessor;
+ name = aName;
}
/**
* Constructs the authorization service.
*/
public DefaultAuthorizationService() {
- _rules = new ArrayList<AuthorizationRule>();
- _userAccessor = null;
- _name = null;
+ rules = new ArrayList<AuthorizationRule>();
+ userAccessor = null;
+ name = null;
}
/**
* @param aUserAccessor User accessor.
*/
public void setUserAccessor(UserAccessor aUserAccessor) {
- _userAccessor = aUserAccessor;
+ userAccessor = aUserAccessor;
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation)
*/
public boolean isAllowed(Object aResource, Operation aOperation) {
- User user = _userAccessor.getCurrentUser();
- for (AuthorizationRule rule: _rules) {
+ User user = userAccessor.getCurrentUser();
+ for (AuthorizationRule rule: rules) {
switch ( rule.isAllowed(aResource, aOperation, user)) {
case DENIED: { return false; }
case GRANTED: { return true; }
}
protected String getName() {
- return _name;
+ return name;
}
public void setName(String aName) {
- _name = aName;
+ name = aName;
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#getRules()
*/
public AuthorizationRule[] getRules() {
- return _rules.toArray(new AuthorizationRule[0]);
+ return rules.toArray(new AuthorizationRule[0]);
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule)
*/
public void appendRule(AuthorizationRule aRule) {
- _rules.add(aRule);
+ rules.add(aRule);
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int, org.wamblee.security.authorization.AuthorizationRule)
*/
public void insertRuleAfter(int aIndex, AuthorizationRule aRule) {
- _rules.add(aIndex, aRule);
+ rules.add(aIndex, aRule);
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#removeRule(int)
*/
public void removeRule(int aIndex) {
- _rules.remove(aIndex);
+ rules.remove(aIndex);
}
/**
* @return The rules.
*/
protected List<AuthorizationRule> getMappedRules() {
- return _rules;
+ return rules;
}
/**
* @param aRules The rules.
*/
protected void setMappedRules(List<AuthorizationRule> aRules) {
- _rules = aRules;
+ rules = aRules;
}
}
*/
public class DefaultOperationRegistry implements OperationRegistry {
- private Map<String,Operation> _operations;
+ private Map<String,Operation> operations;
public DefaultOperationRegistry(Operation[] aOperations) {
- _operations = new TreeMap<String, Operation>();
+ operations = new TreeMap<String, Operation>();
for (Operation operation: aOperations) {
- _operations.put(operation.getName(), operation);
+ operations.put(operation.getName(), operation);
}
}
* @see org.wamblee.security.authorization.OperationRegistry#getOperations(java.lang.Class)
*/
public Operation[] getOperations(Class aResourceClass) {
- return _operations.values().toArray(new Operation[0]);
+ return operations.values().toArray(new Operation[0]);
}
/* (non-Javadoc)
String[] names = aOperationsString.split(",");
ArrayList<Operation> result = new ArrayList<Operation>();
for (String name: names) {
- Operation operation = _operations.get(name);
+ Operation operation = operations.get(name);
if ( operation == null ) {
throw new IllegalArgumentException("Unknown operation '" + name + "'");
}
/**
* Group the user must be in.
*/
- private String _group;
+ private String group;
/**
* Constructs the condition.
* @param aGroup Group the user must be in.
*/
public GroupUserCondition(String aGroup) {
- _group = aGroup;
+ group = aGroup;
}
/**
*
*/
protected GroupUserCondition() {
- _group = null;
+ group = null;
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.UserCondition#matches(org.wamblee.usermgt.UserAccessor)
*/
public boolean matches(User aUser) {
- return aUser.isInGroup(_group);
+ return aUser.isInGroup(group);
}
/**
- * @return Returns the _group.
+ * @return Returns the group.
*/
protected String getGroup() {
- return _group;
+ return group;
}
/**
- * @param _group The _group to set.
+ * @param group The group to set.
*/
protected void setGroup(String aGroup) {
- _group = aGroup;
+ group = aGroup;
}
/* (non-Javadoc)
*/
@Override
public String toString() {
- return "GroupUserCondition(group=" + _group + ")";
+ return "GroupUserCondition(group=" + group + ")";
}
}
/**
* Operation that the other operation must be a subclass of.
*/
- private Class<? extends Operation> _operation;
+ private Class<? extends Operation> operation;
/**
* Constructs the condition.
* Operation that an operation must be an instance of.
*/
public IsaOperationCondition(Class<? extends Operation> aOperation) {
- _operation = aOperation;
+ operation = aOperation;
}
/**
*
*/
public IsaOperationCondition() {
- _operation = null;
+ operation = null;
}
/*
* @see org.wamblee.security.authorization.OperationCondition#matches(org.wamblee.security.authorization.Operation)
*/
public boolean matches(Operation aOperation) {
- return _operation.isInstance(aOperation);
+ return operation.isInstance(aOperation);
}
/**
* @return Operation string.
*/
protected String getOperationString() {
- if (_operation == null) {
+ if (operation == null) {
return null;
}
- return _operation.getName();
+ return operation.getName();
}
/**
return;
}
try {
- _operation = (Class<? extends Operation>)Class.forName(aOperation);
+ operation = (Class<? extends Operation>)Class.forName(aOperation);
} catch (Exception e) {
throw new IllegalArgumentException("Unknown class '" + aOperation + "'");
}
*/
@Override
public String toString() {
- return "IsaOperationCondition(operation=" + _operation.getName() + ")";
+ return "IsaOperationCondition(operation=" + operation.getName() + ")";
}
}
/**
* String the path must start with.
*/
- private String _pattern;
+ private String pattern;
/**
* Constructs the condition.
* @param aPattern String the path must start with.
*/
public RegexpPathCondition(String aPattern) {
- _pattern = aPattern;
+ pattern = aPattern;
}
/**
*
*/
protected RegexpPathCondition() {
- _pattern = null;
+ pattern = null;
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.PathCondition#matches(java.lang.String)
*/
public boolean matches(String aPath) {
- return aPath.matches(_pattern);
+ return aPath.matches(pattern);
}
/**
* @return Returns the _path.
*/
protected String getPattern() {
- return _pattern;
+ return pattern;
}
/**
* @param aPattern The _path to set.
*/
protected void setPattern(String aPattern) {
- _pattern = aPattern;
+ pattern = aPattern;
}
/* (non-Javadoc)
*/
@Override
public String toString() {
- return "RegexpCondition(pattern = '" + _pattern + "')";
+ return "RegexpCondition(pattern = '" + pattern + "')";
}
}
/**
* Result that the rule will return in case there is a match.
*/
- private AuthorizationResult _result;
+ private AuthorizationResult result;
/**
* A condition which specifies which users the rule is for.
*/
- private UserCondition _userCondition;
+ private UserCondition userCondition;
/**
* Path the rule applies for.
*/
- private PathCondition _pathCondition;
+ private PathCondition pathCondition;
/**
* Resource class that the rule applies for.
*/
- private Class _resourceClass;
+ private Class resourceClass;
/**
* Operation that this rule is for.
*/
- private OperationCondition _operationCondition;
+ private OperationCondition operationCondition;
/**
* Constructs an authorization rule.
if ( !aResult.equals(GRANTED) && !aResult.equals(DENIED)) {
throw new IllegalArgumentException("Only GRANTED or DENIED may be used: " + aResult);
}
- _result = aResult;
- _userCondition = aUserCondition;
- _pathCondition = aPathCondition;
- _resourceClass = aResourceClass;
- _operationCondition = aOperationCondition;
+ result = aResult;
+ userCondition = aUserCondition;
+ pathCondition = aPathCondition;
+ resourceClass = aResourceClass;
+ operationCondition = aOperationCondition;
}
/**
*
*/
protected UrlAuthorizationRule(Class aResourceClass) {
- _result = null;
- _userCondition = null;
- _pathCondition = null;
- _resourceClass = aResourceClass;
- _operationCondition = null;
+ result = null;
+ userCondition = null;
+ pathCondition = null;
+ resourceClass = aResourceClass;
+ operationCondition = null;
}
/**
*
*/
protected UrlAuthorizationRule() {
- _result = null;
- _userCondition = null;
- _pathCondition = null;
- _resourceClass = null;
- _operationCondition = null;
+ result = null;
+ userCondition = null;
+ pathCondition = null;
+ resourceClass = null;
+ operationCondition = null;
}
* @see org.wamblee.security.authorization.AuthorizationRule#getSupportedTypes()
*/
public Class[] getSupportedTypes() {
- return new Class[] { _resourceClass };
+ return new Class[] { resourceClass };
}
/*
* org.wamblee.security.authorization.Operation)
*/
public AuthorizationResult isAllowed(Object aResource, Operation anOperation, User aUser) {
- if ( ! _resourceClass.isInstance(aResource)) {
+ if ( ! resourceClass.isInstance(aResource)) {
return UNSUPPORTED_RESOURCE;
}
String path = getResourcePath(aResource);
* @return Authorization result,
*/
protected AuthorizationResult isAllowed(String aPath, Operation aOperation, User aUser) {
- if ( ! _pathCondition.matches(aPath) ) {
+ if ( ! pathCondition.matches(aPath) ) {
return UNDECIDED;
}
- if ( !_operationCondition.matches(aOperation) ) {
+ if ( !operationCondition.matches(aOperation) ) {
return UNDECIDED;
}
- if ( !_userCondition.matches(aUser)) {
+ if ( !userCondition.matches(aUser)) {
return UNDECIDED;
}
- return _result;
+ return result;
}
/**
* Gets the path of the resource.
* @param aResource Resource, guaranteed to be an instance of
- * {@link #_resourceClass}.
+ * {@link #resourceClass}.
* @return Path of the resource.
*/
protected abstract String getResourcePath(Object aResource);
*/
@Override
public String toString() {
- return "UrlAUthorizationRule(result = " + _result +
- ", pathCondition = " + _pathCondition +
- ", userCondition = " + _userCondition +
- ", resourceClass = " + _resourceClass + ")";
+ return "UrlAUthorizationRule(result = " + result +
+ ", pathCondition = " + pathCondition +
+ ", userCondition = " + userCondition +
+ ", resourceClass = " + resourceClass + ")";
}
/**
* @return Result.
*/
protected String getAuthorizationResultString() {
- if ( _result == null ) {
+ if ( result == null ) {
return null;
}
- return _result.toString();
+ return result.toString();
}
/**
* @param aResult Result.
*/
protected void setAuthorizationResultString(String aResult) {
- _result = AuthorizationResult.valueOf(aResult);
+ result = AuthorizationResult.valueOf(aResult);
}
protected String getResourceClassName() {
- if ( _resourceClass == null ) {
+ if ( resourceClass == null ) {
return "";
}
- return _resourceClass.getName();
+ return resourceClass.getName();
}
protected void setResourceClassName(String aResourceClass) {
try {
- _resourceClass = Class.forName(aResourceClass);
+ resourceClass = Class.forName(aResourceClass);
} catch (ClassNotFoundException e) {
LOGGER.error("Cannot find resource class '" + aResourceClass + "'", e);
throw new IllegalArgumentException(e.getMessage(), e);
}
/**
- * @return Returns the _operationCondition.
+ * @return Returns the operationCondition.
*/
public OperationCondition getOperationCondition() {
- return _operationCondition;
+ return operationCondition;
}
/**
- * @param aOperationCondition The _operationCondition to set.
+ * @param aOperationCondition The operationCondition to set.
*/
protected void setOperationCondition(OperationCondition aOperationCondition) {
- _operationCondition = aOperationCondition;
+ operationCondition = aOperationCondition;
}
/**
- * @return Returns the _pathCondition.
+ * @return Returns the pathCondition.
*/
public PathCondition getPathCondition() {
- return _pathCondition;
+ return pathCondition;
}
/**
- * @param aPathCondition The _pathCondition to set.
+ * @param aPathCondition The pathCondition to set.
*/
protected void setPathCondition(PathCondition aPathCondition) {
- _pathCondition = aPathCondition;
+ pathCondition = aPathCondition;
}
/**
- * @return Returns the _userCondition.
+ * @return Returns the userCondition.
*/
public UserCondition getUserCondition() {
- return _userCondition;
+ return userCondition;
}
/**
- * @param aUserCondition The _userCondition to set.
+ * @param aUserCondition The userCondition to set.
*/
protected void setUserCondition(UserCondition aUserCondition) {
- _userCondition = aUserCondition;
+ userCondition = aUserCondition;
}
}
/**
* Authorization service to use.
*/
- private DefaultAuthorizationService _service;
+ private DefaultAuthorizationService service;
/**
* Hibernate template to use.
*/
- private HibernateTemplate _template;
+ private HibernateTemplate template;
/**
* User accessor.
*/
- private UserAccessor _userAccessor;
+ private UserAccessor userAccessor;
/**
* Name of the service.
*/
- private String _name;
+ private String name;
/**
* Refresh interval in milliseconds.
*/
- private final long _refreshInterval;
+ private final long refreshInterval;
/**
* Last refresh time.
*/
- private long _lastRefreshTime;
+ private long lastRefreshTime;
/**
* Constructs the persistent service.
public PersistentAuthorizationService(String aName,
HibernateTemplate aTemplate, UserAccessor aAccessor,
long aRefreshInterval) {
- _template = aTemplate;
- _refreshInterval = aRefreshInterval;
- _lastRefreshTime = System.currentTimeMillis();
- _userAccessor = aAccessor;
- _name = aName;
+ template = aTemplate;
+ refreshInterval = aRefreshInterval;
+ lastRefreshTime = System.currentTimeMillis();
+ userAccessor = aAccessor;
+ name = aName;
}
/**
* Initialize service if needed.
*/
private void initialize() {
- if (_service == null) {
- List<DefaultAuthorizationService> result = _template
+ if (service == null) {
+ List<DefaultAuthorizationService> result = template
.findByNamedQueryAndNamedParam(FIND_QUERY, NAME_PARAM,
- _name);
+ name);
if (result.size() > 1) {
throw new IllegalArgumentException(
- "Returned more than one service for name '" + _name
+ "Returned more than one service for name '" + name
+ "' (" + result.size() + ")");
}
if (result.size() == 0) {
- _service = new DefaultAuthorizationService(_userAccessor, _name);
- _template.persist(_service);
+ service = new DefaultAuthorizationService(userAccessor, name);
+ template.persist(service);
} else {
- _service = result.get(0);
- _service.setUserAccessor(_userAccessor);
+ service = result.get(0);
+ service.setUserAccessor(userAccessor);
}
}
}
public boolean isAllowed(Object aResource, Operation aOperation) {
initialize();
refresh();
- return _service.isAllowed(aResource, aOperation);
+ return service.isAllowed(aResource, aOperation);
}
/* (non-Javadoc)
public <T> T check(T aResource, Operation aOperation) {
initialize();
refresh();
- return _service.check(aResource, aOperation);
+ return service.check(aResource, aOperation);
}
/*
public AuthorizationRule[] getRules() {
initialize();
refresh();
- return _service.getRules();
+ return service.getRules();
}
/*
public void appendRule(AuthorizationRule aRule) {
initialize();
refresh();
- _service.appendRule(aRule);
+ service.appendRule(aRule);
save();
}
public void removeRule(int aIndex) {
initialize();
refresh();
- _service.removeRule(aIndex);
+ service.removeRule(aIndex);
save();
}
public void insertRuleAfter(int aIndex, AuthorizationRule aRule) {
initialize();
refresh();
- _service.insertRuleAfter(aIndex, aRule);
+ service.insertRuleAfter(aIndex, aRule);
save();
}
*/
private synchronized void refresh() {
long time = System.currentTimeMillis();
- if ( time - _lastRefreshTime > _refreshInterval ) {
- _template.refresh(_service);
- _lastRefreshTime = time;
+ if ( time - lastRefreshTime > refreshInterval ) {
+ template.refresh(service);
+ lastRefreshTime = time;
}
}
* Saves any changes to the service state if necessary.
*/
private void save() {
- HibernateSupport.merge(_template, _service);
+ HibernateSupport.merge(template, service);
}
}
/**
* Password validator.
*/
- private NameValidator _passwordValidator;
+ private NameValidator passwordValidator;
/**
* Password encoder.
*/
- private MessageDigester _passwordEncoder;
+ private MessageDigester passwordEncoder;
protected AbstractUserSet(NameValidator aPasswordValidator,
MessageDigester aPasswordEncoder) {
- _passwordValidator = aPasswordValidator;
- _passwordEncoder = aPasswordEncoder;
+ passwordValidator = aPasswordValidator;
+ passwordEncoder = aPasswordEncoder;
}
/**
* @param aUser User.
*/
protected void setPasswordInfo(User aUser) {
- aUser.setPasswordValidator(_passwordValidator);
- aUser.setPasswordEncoder(_passwordEncoder);
+ aUser.setPasswordValidator(passwordValidator);
+ aUser.setPasswordEncoder(passwordEncoder);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.UserSet#createUser(java.lang.String, java.lang.String, org.wamblee.usermgt.Group)
*/
public User createUser(String aUsername, String aPassword, Group aGroup) throws UserMgtException {
- User user = new User(aUsername, aPassword, aGroup, _passwordValidator, _passwordEncoder);
+ User user = new User(aUsername, aPassword, aGroup, passwordValidator, passwordEncoder);
if (contains(user)) {
throw new UserMgtException(DUPLICATE_USER, user);
}
/**
* Group name.
*/
- private String _name;
+ private String name;
/**
* Constructs the group.
*/
Group(String aName) {
super();
- _name = aName;
+ name = aName;
}
public Group(Group aGroup) {
super(aGroup);
- _name = aGroup._name;
+ name = aGroup.name;
}
protected Group() {
super();
- _name = null;
+ name = null;
}
/**
* @return Group name.
*/
public String getName() {
- return _name;
+ return name;
}
/**
* @param aName Group name.
*/
void setName(String aName) {
- _name = aName;
+ name = aName;
}
/* (non-Javadoc)
if ( !( aGroup instanceof Group )) {
return false;
}
- return _name.equals(((Group)aGroup)._name);
+ return name.equals(((Group)aGroup).name);
}
/* (non-Javadoc)
*/
@Override
public int hashCode() {
- return _name.hashCode();
+ return name.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(T)
*/
public int compareTo(Object aGroup) {
- return _name.compareTo(((Group)aGroup)._name);
+ return name.compareTo(((Group)aGroup).name);
}
/* (non-Javadoc)
*/
@Override
public String toString() {
- return "Group(pk = " + getPrimaryKey() + ", name=" + _name + ")";
+ return "Group(pk = " + getPrimaryKey() + ", name=" + name + ")";
}
}
/**
* Groups.
*/
- private Set<Group> _groups;
+ private Set<Group> groups;
/**
* Constructs an empty group set.
*/
public InMemoryGroupSet() {
- _groups = new TreeSet<Group>();
+ groups = new TreeSet<Group>();
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group)
*/
public void groupModified(Group aGroup) {
- _groups.remove(aGroup);
- _groups.add(aGroup);
+ groups.remove(aGroup);
+ groups.add(aGroup);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#find(java.lang.String)
*/
public Group find(String aName) {
- for (Group group: _groups) {
+ for (Group group: groups) {
if ( group.getName().equals(aName)) {
return new Group(group);
}
* @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group)
*/
public boolean contains(Group aGroup) {
- return _groups.contains(aGroup);
+ return groups.contains(aGroup);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group)
*/
public boolean add(Group aGroup) {
- return _groups.add(aGroup);
+ return groups.add(aGroup);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group)
*/
public boolean remove(Group aGroup) {
- return _groups.remove(aGroup);
+ return groups.remove(aGroup);
}
/* (non-Javadoc)
*/
public Set<Group> list() {
Set<Group> list = new TreeSet<Group>();
- for (Group group: _groups) {
+ for (Group group: groups) {
list.add(new Group(group));
}
return list;
* @see org.wamblee.usermgt.GroupSet#size()
*/
public int size() {
- return _groups.size();
+ return groups.size();
}
}
/**
* Users. All users in this set have their password validator and encoder set.
*/
- private Set<User> _users;
+ private Set<User> users;
/**
* Constructs an empty user set.
*/
public InMemoryUserSet(NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) {
super(aPasswordValidator, aPasswordEncoder);
- _users = new TreeSet<User>();
+ users = new TreeSet<User>();
}
/*
* @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User)
*/
public void userModified(User aUser) {
- _users.remove(aUser);
+ users.remove(aUser);
setPasswordInfo(aUser);
- _users.add(aUser);
+ users.add(aUser);
}
/*
* @see org.wamblee.usermgt.UserSet#find(java.lang.String)
*/
public User find(String aName) {
- for (User user : _users) {
+ for (User user : users) {
if (user.getName().equals(aName)) {
return new User(user);
}
*/
public boolean add(User aUser) {
setPasswordInfo(aUser);
- return _users.add(aUser);
+ return users.add(aUser);
}
/*
* @see org.wamblee.usermgt.UserSet#contains(org.wamblee.usermgt.User)
*/
public boolean contains(User aUser) {
- return _users.contains(aUser);
+ return users.contains(aUser);
}
/*
* @see org.wamblee.usermgt.UserSet#remove(org.wamblee.usermgt.User)
*/
public boolean remove(User aUser) {
- return _users.remove(aUser);
+ return users.remove(aUser);
}
/*
*/
public Set<User> list() {
Set<User> list = new TreeSet<User>();
- for (User user : _users) {
+ for (User user : users) {
list.add(new User(user));
}
return list;
*/
public Set<User> list(Group aGroup) {
Set<User> result = new TreeSet<User>();
- for (User user : _users) {
+ for (User user : users) {
if (user.getGroups().contains(aGroup)) {
result.add(new User(user));
}
* @see org.wamblee.usermgt.UserSet#size()
*/
public int size() {
- return _users.size();
+ return users.size();
}
}
/**
* User administration to use.
*/
- private UserAdministration _admin;
+ private UserAdministration admin;
/**
* Class of the JAAS user principal.
*/
- private Class _userPrincipalClass;
+ private Class userPrincipalClass;
/**
* Constructs user accessor.
* @param aUserClassName Class name of the user principal.
*/
public JaasUserAccessor(UserAdministration aAdmin, String aUserClassName) {
- _admin = aAdmin;
+ admin = aAdmin;
try {
- _userPrincipalClass = Class.forName(aUserClassName);
- if ( !Principal.class.isAssignableFrom(_userPrincipalClass)) {
+ userPrincipalClass = Class.forName(aUserClassName);
+ if ( !Principal.class.isAssignableFrom(userPrincipalClass)) {
throw new IllegalArgumentException("Specified class '" + aUserClassName + "' is not a subclass of '" +
Principal.class.getName());
}
}
Principal userPrincipal = getUserPrincipal(subject);
- return _admin.getUser(userPrincipal.getName());
+ return admin.getUser(userPrincipal.getName());
}
/**
Set<Principal> principals = subject.getPrincipals();
Principal userPrincipal = null;
for ( Principal principal: principals) {
- if ( principal.getClass().equals(_userPrincipalClass)) {
+ if ( principal.getClass().equals(userPrincipalClass)) {
if ( userPrincipal != null ) {
throw new IllegalArgumentException(
- "Multiple principals for class '" + _userPrincipalClass + "', subject: " + subject);
+ "Multiple principals for class '" + userPrincipalClass + "', subject: " + subject);
}
userPrincipal = principal;
}
}
if ( userPrincipal == null ) {
throw new IllegalArgumentException(
- "No user principal found for class '" + _userPrincipalClass + "', subject: " + subject);
+ "No user principal found for class '" + userPrincipalClass + "', subject: " + subject);
}
return userPrincipal;
}
/**
* Pattern to use.
*/
- private String _pattern;
+ private String pattern;
/**
* Reason to use when validation fails.
*/
- private Reason _reason;
+ private Reason reason;
/**
* Message to report.
*/
- private String _message;
+ private String message;
/**
* Validates a regular expression.
* @param aMessage Message to report.
*/
public RegexpNameValidator(String aPattern, Reason aReason, String aMessage) {
- _pattern = aPattern;
- _reason = aReason;
- _message = aMessage;
+ pattern = aPattern;
+ reason = aReason;
+ message = aMessage;
}
/**
* @see org.wamblee.usermgt.NameValidator#validate(java.lang.String)
*/
public void validate(String aName) throws UserMgtException {
- if ( !aName.matches(_pattern)) {
- throw new UserMgtException(_reason, _message);
+ if ( !aName.matches(pattern)) {
+ throw new UserMgtException(reason, message);
}
}
/**
* User name.
*/
- private String _name;
+ private String name;
/**
* Password.
*/
- private String _password;
+ private String password;
/**
* Groups the user belongs to.
*/
- private Set<Group> _groups;
+ private Set<Group> groups;
/**
* Password validator.
*/
- private NameValidator _passwordValidator;
+ private NameValidator passwordValidator;
/**
* Password encoder.
*/
- private MessageDigester _passwordEncoder;
+ private MessageDigester passwordEncoder;
/**
* Constructs the user.
User(String aName, String aPassword, Group aGroup, NameValidator aPasswordValidator,
MessageDigester aPasswordEncoder) throws UserMgtException {
super();
- _name = aName;
+ name = aName;
aPasswordValidator.validate(aPassword);
- _password = aPasswordEncoder.hash(aPassword);
- _groups = new TreeSet<Group>();
- _groups.add(aGroup);
- _passwordValidator = aPasswordValidator;
- _passwordEncoder = aPasswordEncoder;
+ password = aPasswordEncoder.hash(aPassword);
+ groups = new TreeSet<Group>();
+ groups.add(aGroup);
+ passwordValidator = aPasswordValidator;
+ passwordEncoder = aPasswordEncoder;
}
public User(User aUser) {
super(aUser);
- _name = aUser._name;
- _password = aUser._password;
- _groups = new TreeSet<Group>();
- for (Group group: aUser._groups) {
- _groups.add(new Group(group));
+ name = aUser.name;
+ password = aUser.password;
+ groups = new TreeSet<Group>();
+ for (Group group: aUser.groups) {
+ groups.add(new Group(group));
}
- _passwordValidator = aUser._passwordValidator;
- _passwordEncoder = aUser._passwordEncoder;
+ passwordValidator = aUser.passwordValidator;
+ passwordEncoder = aUser.passwordEncoder;
}
User() {
super();
- _name = null;
- _password = null;
- _groups = null;
- _passwordValidator = null;
- _passwordEncoder = null;
+ name = null;
+ password = null;
+ groups = null;
+ passwordValidator = null;
+ passwordEncoder = null;
}
/**
* @param aPasswordValidator Validator.
*/
public void setPasswordValidator(NameValidator aPasswordValidator) {
- _passwordValidator = aPasswordValidator;
+ passwordValidator = aPasswordValidator;
}
/**
* @param aPasswordEncoder Encoder.
*/
public void setPasswordEncoder(MessageDigester aPasswordEncoder) {
- _passwordEncoder = aPasswordEncoder;
+ passwordEncoder = aPasswordEncoder;
}
/**
- * @return Returns the _password.
+ * @return Returns the password.
*/
String getPassword() {
- return _password;
+ return password;
}
/**
* @throws UserMgtException In case the password is incorrect.
*/
public void checkPassword(String aPassword) throws UserMgtException {
- String encoded = _passwordEncoder.hash(aPassword);
- if ( !_password.equals(encoded) ) {
+ String encoded = passwordEncoder.hash(aPassword);
+ if ( !password.equals(encoded) ) {
throw new UserMgtException(Reason.INVALID_PASSWORD, this);
}
}
*/
public void changePassword(String aOldPassword, String aNewPassword) throws UserMgtException {
checkPassword(aOldPassword);
- _passwordValidator.validate(aNewPassword);
+ passwordValidator.validate(aNewPassword);
setPassword(aNewPassword);
}
* The password to set.
*/
public void setPassword(String aPassword) throws UserMgtException {
- _passwordValidator.validate(aPassword);
- _password = _passwordEncoder.hash(aPassword);
+ passwordValidator.validate(aPassword);
+ password = passwordEncoder.hash(aPassword);
}
/**
* @return Password.
*/
protected String getPasswordString() {
- return _password;
+ return password;
}
/**
* @param aPassword Password.
*/
protected void setPasswordString(String aPassword) {
- _password = aPassword;
+ password = aPassword;
}
/**
* @return Returns the _user.
*/
public String getName() {
- return _name;
+ return name;
}
/**
* The username to set.
*/
void setName(String aName) {
- _name = aName;
+ name = aName;
}
/**
*/
public Set<Group> getGroups() {
Set<Group> result = new TreeSet<Group>();
- result.addAll(_groups);
+ result.addAll(groups);
return result;
}
* @return True if the user belongs to the group.
*/
public boolean isInGroup(Group aGroup) {
- return _groups.contains(aGroup);
+ return groups.contains(aGroup);
}
/**
* @return True if the user belongs to the group.
*/
public boolean isInGroup(String aGroup) {
- return _groups.contains(new Group(aGroup));
+ return groups.contains(new Group(aGroup));
}
/**
* @return set of groups.
*/
Set<Group> getGroupSet() {
- return _groups;
+ return groups;
}
/**
* @param aGroups Groups.
*/
void setGroupSet(Set<Group> aGroups) {
- _groups = aGroups;
+ groups = aGroups;
}
/**
* @throws UserMgtException In case the user already belongs to the group.
*/
void addGroup(Group aGroup) throws UserMgtException {
- if (_groups.contains(aGroup)) {
+ if (groups.contains(aGroup)) {
throw new UserMgtException(Reason.USER_ALREADY_IN_GROUP, aGroup);
}
- _groups.add(aGroup);
+ groups.add(aGroup);
}
/**
* @throws UserMgtException In case the user does not belong to the group.
*/
void removeGroup(Group aGroup) throws UserMgtException {
- if (!_groups.contains(aGroup)) {
+ if (!groups.contains(aGroup)) {
throw new UserMgtException(Reason.USER_NOT_IN_GROUP, this, aGroup);
}
- if ( _groups.size() == 1 ) {
+ if ( groups.size() == 1 ) {
throw new UserMgtException(Reason.USER_MUST_BE_IN_A_GROUP, this, aGroup);
}
- _groups.remove(aGroup);
+ groups.remove(aGroup);
}
/* (non-Javadoc)
return false;
}
User user = (User)aUser;
- return _name.equals(user._name);
+ return name.equals(user.name);
}
/* (non-Javadoc)
*/
@Override
public int hashCode() {
- return _name.hashCode();
+ return name.hashCode();
}
/* (non-Javadoc)
*/
@Override
public String toString() {
- String result = "User(name=" + _name + ", password=" + _password;
- for (Group group: _groups) {
+ String result = "User(name=" + name + ", password=" + password;
+ for (Group group: groups) {
result += ", group=" + group;
}
return result + ")";
* @see java.lang.Comparable#compareTo(T)
*/
public int compareTo(Object aUser) {
- return _name.compareTo(((User)aUser)._name);
+ return name.compareTo(((User)aUser).name);
}
}
/**
* All known users.
*/
- private UserSet _users;
+ private UserSet users;
/**
* All known groups.
*/
- private GroupSet _groups;
+ private GroupSet groups;
/**
* Validator for user names.
*/
- private NameValidator _userValidator;
+ private NameValidator userValidator;
/**
* Validator for group names.
*/
- private NameValidator _groupValidator;
+ private NameValidator groupValidator;
/**
* Constructs empty user administration.
*/
public UserAdministrationImpl(UserSet aUsers, GroupSet aGroups, NameValidator aUserValidator,
NameValidator aGroupValidator) {
- _users = aUsers;
- _groups = aGroups;
- _userValidator = aUserValidator;
- _groupValidator = aGroupValidator;
+ users = aUsers;
+ groups = aGroups;
+ userValidator = aUserValidator;
+ groupValidator = aGroupValidator;
}
/*
*/
public User createUser(String aUser, String aPassword, Group aGroup)
throws UserMgtException {
- _userValidator.validate(aUser);
+ userValidator.validate(aUser);
checkGroup(aGroup);
- User user = _users.createUser(aUser, aPassword, aGroup);
+ User user = users.createUser(aUser, aPassword, aGroup);
return new User(user);
}
* @see org.wamblee.usermgt.UserAdministration#createGroup(java.lang.String)
*/
public Group createGroup(String aName) throws UserMgtException {
- _groupValidator.validate(aName);
+ groupValidator.validate(aName);
Group group = new Group(aName);
- if (_groups.contains(group)) {
+ if (groups.contains(group)) {
throw new UserMgtException(DUPLICATE_GROUP, group);
}
- _groups.add(group);
+ groups.add(group);
return new Group(group);
}
* @see org.wamblee.usermgt.UserAdministration#userModified(org.wamblee.usermgt.User)
*/
public void userModified(User aUser) {
- _users.userModified(aUser);
+ users.userModified(aUser);
}
/*
* @see org.wamblee.usermgt.UserAdministration#groupModified(org.wamblee.usermgt.Group)
*/
public void groupModified(Group aGroup) {
- _groups.groupModified(aGroup);
+ groups.groupModified(aGroup);
}
/*
* @see org.wamblee.usermgt.UserAdministration#getUser(java.lang.String)
*/
public User getUser(String aName) {
- return _users.find(aName);
+ return users.find(aName);
}
/*
* @see org.wamblee.usermgt.UserAdministration#getGroup(java.lang.String)
*/
public Group getGroup(String aName) {
- return _groups.find(aName);
+ return groups.find(aName);
}
/*
* @see org.wamblee.usermgt.UserAdministration#getUsers()
*/
public Set<User> getUsers() {
- return _users.list();
+ return users.list();
}
/*
* @see org.wamblee.usermgt.UserAdministration#getUsers(org.wamblee.usermgt.Group)
*/
public Set<User> getUsers(Group aGroup) {
- return _users.list(aGroup);
+ return users.list(aGroup);
}
/*
* @see org.wamblee.usermgt.UserAdministration#getGroups()
*/
public Set<Group> getGroups() {
- return _groups.list();
+ return groups.list();
}
/*
*/
public void removeUser(User aUser) throws UserMgtException {
checkUser(aUser);
- _users.remove(aUser);
+ users.remove(aUser);
}
/*
if (getUsers(aGroup).size() > 0) {
throw new UserMgtException(GROUP_STILL_OCCUPIED, aGroup);
}
- _groups.remove(aGroup);
+ groups.remove(aGroup);
}
/*
if (aUser.getName().equals(aUserName)) {
throw new UserMgtException(TRIVIAL_RENAME, aUser);
}
- if (_users.find(aUserName) != null) {
+ if (users.find(aUserName) != null) {
throw new UserMgtException(DUPLICATE_USER, aUser);
}
- _userValidator.validate(aUserName);
+ userValidator.validate(aUserName);
// we are modifying the user so we should re-insert it into the set
// after renaming it.
- _users.remove(aUser);
+ users.remove(aUser);
aUser.setName(aUserName);
- _users.add(aUser);
+ users.add(aUser);
}
/*
if (aGroup.getName().equals(aGroupName)) {
throw new UserMgtException(TRIVIAL_RENAME, aGroup);
}
- if (_groups.find(aGroupName) != null) {
+ if (groups.find(aGroupName) != null) {
throw new UserMgtException(DUPLICATE_GROUP, aGroup);
}
- _groupValidator.validate(aGroupName);
+ groupValidator.validate(aGroupName);
// we are renaming the group so we should re-insert it into the set
// after renaming it.
- _groups.remove(aGroup);
+ groups.remove(aGroup);
aGroup.setName(aGroupName);
- _groups.add(aGroup);
+ groups.add(aGroup);
}
/*
checkUser(aUser);
checkGroup(aGroup);
aUser.addGroup(aGroup);
- _users.userModified(aUser);
+ users.userModified(aUser);
}
/*
checkUser(aUser);
checkGroup(aGroup);
aUser.removeGroup(aGroup);
- _users.userModified(aUser);
+ users.userModified(aUser);
}
/**
* @throws UserMgtException
*/
private void checkUser(User aUser) throws UserMgtException {
- if (!_users.contains(aUser)) {
+ if (!users.contains(aUser)) {
throw new UserMgtException(UNKNOWN_USER, aUser);
}
}
* @throws UserMgtException
*/
private void checkGroup(Group aGroup) throws UserMgtException {
- if (!_groups.contains(aGroup)) {
+ if (!groups.contains(aGroup)) {
throw new UserMgtException(UNKNOWN_GROUP, aGroup);
}
}
* @see org.wamblee.usermgt.UserAdministration#getUserCount()
*/
public int getUserCount() {
- return _users.size();
+ return users.size();
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.UserAdministration#getGroupCount()
*/
public int getGroupCount() {
- return _groups.size();
+ return groups.size();
}
}
/**
* Cause of the exception.
*/
- private Reason _cause;
+ private Reason cause;
/**
* User or null if no user is relevant for the problem.
*/
- private User _user;
+ private User user;
/**
* Group or null if no group is relevant for the problem.
*/
- private Group _group;
+ private Group group;
public UserMgtException(Reason aCause, String aMessage) {
super(MESSAGES.get(aCause) + ": " + aMessage);
- _cause = aCause;
+ cause = aCause;
}
public UserMgtException(Reason aCause, User aUser) {
this(aCause, "for user '" + aUser.getName() + "'");
- _user = aUser;
+ user = aUser;
}
public UserMgtException(Reason aCause, Group aGroup) {
this(aCause, "for group '" + aGroup.getName() + "'");
- _group = aGroup;
+ group = aGroup;
}
public UserMgtException(Reason aCause, User aUser, Group aGroup) {
this(aCause, "for user '" + aUser.getName() + "' and group '" + aGroup.getName() + "'");
- _user = aUser;
- _group = aGroup;
+ user = aUser;
+ group = aGroup;
}
/**
* @return Cause.
*/
public Reason getReason() {
- return _cause;
+ return cause;
}
/**
* @return User or null if not applicable.
*/
public User getUser() {
- return _user;
+ return user;
}
/**
* @return Group or null if not applicable.
*/
public Group getGroup() {
- return _group;
+ return group;
}
}
/**
* Cache of users. Every user in the cache has its password validator and encoder set.
*/
- private Cache<String, User> _cache;
+ private Cache<String, User> cache;
/**
* Spring hibernate support.
*/
- private HibernateSupport _hibernateSupport;
+ private HibernateSupport hibernateSupport;
/**
* Constructs a user set backed by the database.
public HibernateUserSet(Cache<String,User> aCache,
NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) {
super(aPasswordValidator, aPasswordEncoder);
- _cache = aCache;
- _hibernateSupport = new HibernateSupport();
+ cache = aCache;
+ hibernateSupport = new HibernateSupport();
}
/**
* @param aFactory Session factory.
*/
public void setSessionFactory(SessionFactory aFactory) {
- _hibernateSupport.setSessionFactory(aFactory);
+ hibernateSupport.setSessionFactory(aFactory);
}
/**
* @return Hibernate template.
*/
private HibernateTemplate getHibernateTemplate() {
- return _hibernateSupport.getHibernateTemplate();
+ return hibernateSupport.getHibernateTemplate();
}
/*
*/
public void userModified(User aUser) {
assert aUser.getPrimaryKey() != null;
- _hibernateSupport.merge(aUser);
- _cache.remove(aUser.getName());
+ hibernateSupport.merge(aUser);
+ cache.remove(aUser.getName());
setPasswordInfo(aUser);
- _cache.put(aUser.getName(), new User(aUser));
+ cache.put(aUser.getName(), new User(aUser));
}
/*
* @see org.wamblee.usermgt.UserSet#find(java.lang.String)
*/
public User find(String aName) {
- User user = _cache.get(aName);
+ User user = cache.get(aName);
if (user != null) {
return user;
}
}
user = (User) result.get(0);
setPasswordInfo(user);
- _cache.put(aName, user);
+ cache.put(aName, user);
return new User(user);
}
}
getHibernateTemplate().saveOrUpdate(aUser);
setPasswordInfo(aUser);
- _cache.put(aUser.getName(), aUser);
+ cache.put(aUser.getName(), aUser);
return true;
}
getHibernateTemplate().delete(user);
aUser.setPersistedVersion(-1);
aUser.setPrimaryKey(null);
- _cache.remove(aUser.getName());
+ cache.remove(aUser.getName());
return true;
}
mappingFilesConfig.getSetterConfig().initAllSetters();
addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), mappingFilesConfig);
- Component<?> _hibernate = new HibernateComponent("hibernate");
- addComponent(_hibernate);
+ Component<?> hibernate = new HibernateComponent("hibernate");
+ addComponent(hibernate);
- Component<?> _repository = new UserGroupRepositoryComponent("usersgroups");
- addComponent(_repository);
+ Component<?> repository = new UserGroupRepositoryComponent("usersgroups");
+ addComponent(repository);
- Component<?> _usermgt = new UserAdministrationLightComponent("usermgtlight");
- addComponent(_usermgt);
+ Component<?> usermgt = new UserAdministrationLightComponent("usermgtlight");
+ addComponent(usermgt);
addRequiredInterface(new DefaultRequiredInterface("datasource",
DataSource.class));
*/
public class AuthorizationServiceTest extends TestCase {
- private AuthorizationRule _rule1;
- private AuthorizationRule _rule2;
- private AuthorizationRule _rule3;
- private AuthorizationService _service;
+ private AuthorizationRule rule1;
+ private AuthorizationRule rule2;
+ private AuthorizationRule rule3;
+ private AuthorizationService service;
protected AuthorizationService getService() {
- return _service;
+ return service;
}
/* (non-Javadoc)
protected void setUp() throws Exception {
super.setUp();
- _rule1 = createRule(GRANTED, "users", "/oni/", AllOperation.class);
- _rule2 = createRule(DENIED, "users", "/abc/", ReadOperation.class);
- _rule3 = createRule(GRANTED, "users", "/abc/", AllOperation.class);
+ rule1 = createRule(GRANTED, "users", "/oni/", AllOperation.class);
+ rule2 = createRule(DENIED, "users", "/abc/", ReadOperation.class);
+ rule3 = createRule(GRANTED, "users", "/abc/", AllOperation.class);
- _service = createService();
- _service.appendRule(_rule1);
- _service.appendRule(_rule2);
- _service.appendRule(_rule3);
+ service = createService();
+ service.appendRule(rule1);
+ service.appendRule(rule2);
+ service.appendRule(rule3);
}
protected void resetTestRules() {
- ((TestAuthorizationRule)_rule1).reset();
- ((TestAuthorizationRule)_rule2).reset();
- ((TestAuthorizationRule)_rule3).reset();
+ ((TestAuthorizationRule)rule1).reset();
+ ((TestAuthorizationRule)rule2).reset();
+ ((TestAuthorizationRule)rule3).reset();
}
protected UserAccessor createUserAccessor() {
*
*/
public void testFirstRuleGrants() {
- assertTrue( _service.isAllowed(createResource("/oni/xyz.jpg"), new ReadOperation()));
- checkMatchCount(1, _rule1);
- assertTrue(_service.isAllowed(createResource("/oni/xyz.jpg"), new WriteOperation()));
- checkMatchCount(2, _rule1);
- assertTrue(_service.isAllowed(createResource("/oni/xyz.jpg"), new DeleteOperation()));
- checkMatchCount(3, _rule1);
- assertTrue(_service.isAllowed(createResource("/oni/xyz.jpg"), new CreateOperation()));
- checkMatchCount(4, _rule1);
- checkMatchCount(0, _rule2);
- checkMatchCount(0, _rule3);
+ assertTrue( service.isAllowed(createResource("/oni/xyz.jpg"), new ReadOperation()));
+ checkMatchCount(1, rule1);
+ assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), new WriteOperation()));
+ checkMatchCount(2, rule1);
+ assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), new DeleteOperation()));
+ checkMatchCount(3, rule1);
+ assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), new CreateOperation()));
+ checkMatchCount(4, rule1);
+ checkMatchCount(0, rule2);
+ checkMatchCount(0, rule3);
}
/**
*
*/
public void testSecondRuleDenies() {
- assertFalse(_service.isAllowed(createResource("/abc/xyz.jpg"), new ReadOperation()));
- checkMatchCount(0, _rule1);
- checkMatchCount(1, _rule2);
- checkMatchCount(0, _rule3);
+ assertFalse(service.isAllowed(createResource("/abc/xyz.jpg"), new ReadOperation()));
+ checkMatchCount(0, rule1);
+ checkMatchCount(1, rule2);
+ checkMatchCount(0, rule3);
}
/**
*
*/
public void testThirdRuleGrants() {
- assertTrue(_service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation()));
- checkMatchCount(0, _rule1);
- checkMatchCount(0, _rule2);
- checkMatchCount(1, _rule3);
+ assertTrue(service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation()));
+ checkMatchCount(0, rule1);
+ checkMatchCount(0, rule2);
+ checkMatchCount(1, rule3);
}
/**
*/
public void testRemoveRule() {
checkRuleCount(3);
- assertTrue(_service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation()));
- _service.removeRule(2);
- assertFalse(_service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation()));
+ assertTrue(service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation()));
+ service.removeRule(2);
+ assertFalse(service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation()));
checkRuleCount(2);
}
*/
public void testInsertRule() {
checkRuleCount(3);
- assertFalse(_service.isAllowed(createResource("/janse/xyz.jpg"), new WriteOperation()));
- _service.appendRule(createRule(GRANTED, "users", "/janse/", WriteOperation.class));
- assertTrue(_service.isAllowed(createResource("/janse/xyz.jpg"), new WriteOperation()));
+ assertFalse(service.isAllowed(createResource("/janse/xyz.jpg"), new WriteOperation()));
+ service.appendRule(createRule(GRANTED, "users", "/janse/", WriteOperation.class));
+ assertTrue(service.isAllowed(createResource("/janse/xyz.jpg"), new WriteOperation()));
checkRuleCount(4);
}
*
*/
public void testGetRules() {
- AuthorizationRule[] rules = _service.getRules();
+ AuthorizationRule[] rules = service.getRules();
assertEquals(3, rules.length);
}
*
*/
public void testNoRulesSupportResource() {
- assertFalse(_service.isAllowed(createResource("/xyxyxyxy"), new ReadOperation()));
- checkMatchCount(0, _rule1);
- checkMatchCount(0, _rule2);
- checkMatchCount(0, _rule3);
+ assertFalse(service.isAllowed(createResource("/xyxyxyxy"), new ReadOperation()));
+ checkMatchCount(0, rule1);
+ checkMatchCount(0, rule2);
+ checkMatchCount(0, rule3);
}
}
*/
public class DefaultOperationRegistryTest extends TestCase {
- private OperationRegistry _registry;
+ private OperationRegistry registry;
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
@Override
protected void setUp() throws Exception {
- _registry = new DefaultOperationRegistry(new Operation[] {
+ registry = new DefaultOperationRegistry(new Operation[] {
new AllOperation(),
new ReadOperation(),
new WriteOperation(),
*
*/
public void testEncodeDecodeNooperations() {
- assertEquals("", _registry.encode(new Operation[0]));
- assertEquals(0, _registry.decode(Object.class, "").length);
+ assertEquals("", registry.encode(new Operation[0]));
+ assertEquals(0, registry.decode(Object.class, "").length);
}
/**
*
*/
public void testEncode() {
- assertEquals("read,write", _registry.encode(new Operation[] { new ReadOperation(), new WriteOperation() }));
+ assertEquals("read,write", registry.encode(new Operation[] { new ReadOperation(), new WriteOperation() }));
}
/**
*
*/
public void testDecode() {
- Operation[] operations = _registry.decode(Object.class, "read,write");
+ Operation[] operations = registry.decode(Object.class, "read,write");
assertTrue( operations[0] instanceof ReadOperation);
assertTrue( operations[1] instanceof WriteOperation);
}
*/
public void testDecodeUnknownOperation() {
try {
- _registry.decode(Object.class, "bla");
+ registry.decode(Object.class, "bla");
fail();
} catch (IllegalArgumentException e) {
// ok
/**
* Counts the number of matches.
*/
- private int _matches = 0;
+ private int matches = 0;
public TestAuthorizationRule( AuthorizationResult aResult, String aGroup,
String aPath, Class<? extends Operation> aOperation) {
AuthorizationResult result = super.isAllowed(aResource, anOperation, aUser);
if ( result.equals(GRANTED) || result.equals(DENIED)) {
- _matches++;
+ matches++;
}
return result;
}
public int getMatchCount() {
- return _matches;
+ return matches;
}
public void reset() {
- _matches = 0;
+ matches = 0;
}
}
*/
public class TestResource {
- private String _path;
+ private String path;
public TestResource(String aPath) {
- _path = aPath;
+ path = aPath;
}
public String getPath() {
- return _path;
+ return path;
}
}
private static final String PATHCOND_TABLE = "PATH_CONDITIONS";
private static final String USERCOND_TABLE = "USER_CONDITIONS";
- private DefaultContainer _container;
- private Scope _scope;
+ private DefaultContainer container;
+ private Scope scope;
- private DatabaseTesterComponent _databaseTester;
- private UserAccessor _userAccessor;
- private HibernateTemplate _hibernateTemplate;
- private AuthorizationService _authorizationService;
+ private DatabaseTesterComponent databaseTester;
+ private UserAccessor userAccessor;
+ private HibernateTemplate hibernateTemplate;
+ private AuthorizationService authorizationService;
@Override
protected void setUp() throws Exception {
- _container = new DefaultContainer("top");
- DatabaseComponentFactory.addDatabaseConfig(_container);
- _container.addComponent(new DatasourceComponent("datasource"));
+ container = new DefaultContainer("top");
+ DatabaseComponentFactory.addDatabaseConfig(container);
+ container.addComponent(new DatasourceComponent("datasource"));
ClassConfiguration useraccessorConfig = new ClassConfiguration(
TestUserAccessor.class);
useraccessorConfig.getObjectConfig().getSetterConfig().initAllSetters();
- _container.addComponent("userAccessor", useraccessorConfig);
- _container.addComponent(new AuthorizationComponent("authorization",
+ container.addComponent("userAccessor", useraccessorConfig);
+ container.addComponent(new AuthorizationComponent("authorization",
true));
ClassConfiguration dbtesterConfig = new ClassConfiguration(
DatabaseTesterComponent.class);
dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
- _container.addComponent("databaseTester", dbtesterConfig);
+ container.addComponent("databaseTester", dbtesterConfig);
ObjectConfiguration config = new ObjectConfiguration(
PersistentAuthorizationServiceTest.class);
config.getSetterConfig().clear().add("setUserAccessor").add(
"setDatabaseTester").add("setHibernateTemplate").add(
"setAuthorizationService");
- _container.addComponent("testcase", this, config);
+ container.addComponent("testcase", this, config);
- _scope = _container.start();
+ scope = container.start();
- _databaseTester.cleanDatabase();
+ databaseTester.cleanDatabase();
super.setUp();
}
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
- _databaseTester = aDatabaseTester;
+ databaseTester = aDatabaseTester;
}
public void setUserAccessor(UserAccessor aUserAccessor) {
- _userAccessor = aUserAccessor;
+ userAccessor = aUserAccessor;
}
public void setHibernateTemplate(HibernateTemplate aHibernateTemplate) {
- _hibernateTemplate = aHibernateTemplate;
+ hibernateTemplate = aHibernateTemplate;
}
public void setAuthorizationService(
AuthorizationService aAuthorizationService) {
- _authorizationService = aAuthorizationService;
+ authorizationService = aAuthorizationService;
}
/*
@Override
protected AuthorizationService createService() {
PersistentAuthorizationService service = new PersistentAuthorizationService(
- "DEFAULT", _hibernateTemplate, createUserAccessor(), 10000);
+ "DEFAULT", hibernateTemplate, createUserAccessor(), 10000);
return service;
}
@Override
protected void checkRuleCount(int aCount) {
try {
- assertEquals(1, _databaseTester.getTableSize(SERVICE_TABLE));
- assertEquals(aCount, _databaseTester.getTableSize(RULES_TABLE));
- assertEquals(aCount, _databaseTester
+ assertEquals(1, databaseTester.getTableSize(SERVICE_TABLE));
+ assertEquals(aCount, databaseTester.getTableSize(RULES_TABLE));
+ assertEquals(aCount, databaseTester
.getTableSize(SERVICE_RULES_TABLE));
- assertEquals(aCount, _databaseTester.getTableSize(USERCOND_TABLE));
- assertEquals(aCount, _databaseTester.getTableSize(PATHCOND_TABLE));
- assertEquals(aCount, _databaseTester
+ assertEquals(aCount, databaseTester.getTableSize(USERCOND_TABLE));
+ assertEquals(aCount, databaseTester.getTableSize(PATHCOND_TABLE));
+ assertEquals(aCount, databaseTester
.getTableSize(OPERATIONCOND_TABLE));
} catch (SQLException e) {
throw new RuntimeException(e);
*/
public class InMemoryGroupSetTest extends TestCase {
- protected GroupSet _groups;
+ protected GroupSet groups;
/**
* This method must be overriden in subclasses.
@Override
protected void setUp() throws Exception {
super.setUp();
- _groups = createGroupSet();
+ groups = createGroupSet();
checkGroupCount(0);
}
* @param aSize Expected number of groups.
*/
protected void checkGroupCount(int aSize) throws SQLException {
- assertEquals(aSize, _groups.size());
+ assertEquals(aSize, groups.size());
}
/**
*/
public void testAdd() throws SQLException {
Group group = new Group("group1");
- assertTrue( _groups.add(group) );
+ assertTrue( groups.add(group) );
checkGroupExists(group.getName());
checkGroupCount(1);
- Group group2 = _groups.find("group1");
+ Group group2 = groups.find("group1");
assertNotNull(group2);
assertEquals(group.getName(), group2.getName());
- Set<Group> set = _groups.list();
+ Set<Group> set = groups.list();
assertEquals(1, set.size());
assertTrue(set.contains(group));
}
public void testFindUnknownGroup() throws SQLException {
Group group1 = new Group("group1");
Group group2 = new Group("group2");
- _groups.add(group1);
- _groups.add(group2);
+ groups.add(group1);
+ groups.add(group2);
checkGroupExists(group1.getName());
checkGroupExists(group2.getName());
- assertNull( _groups.find("group3") );
+ assertNull( groups.find("group3") );
checkGroupNotExists("group3");
}
*/
public void testAddDuplicateGroup() throws SQLException {
Group group1 = new Group("group1");
- _groups.add(group1);
+ groups.add(group1);
- assertEquals(1, _groups.list().size());
- assertTrue(_groups.contains(group1));
+ assertEquals(1, groups.list().size());
+ assertTrue(groups.contains(group1));
group1 = new Group("group1");
- assertFalse(_groups.add(group1));
- assertEquals(1, _groups.list().size());
+ assertFalse(groups.add(group1));
+ assertEquals(1, groups.list().size());
checkGroupExists(group1.getName());
checkGroupCount(1);
*/
public void testRemoveGroup() throws SQLException {
Group group1 = new Group("group1");
- _groups.add(group1);
- assertTrue(_groups.contains(group1));
+ groups.add(group1);
+ assertTrue(groups.contains(group1));
checkGroupCount(1);
- assertTrue(_groups.remove(group1));
- assertFalse(_groups.contains(group1));
- assertNull(_groups.find(group1.getName()));
- assertEquals(0, _groups.list().size());
+ assertTrue(groups.remove(group1));
+ assertFalse(groups.contains(group1));
+ assertNull(groups.find(group1.getName()));
+ assertEquals(0, groups.list().size());
checkGroupCount(0);
}
*/
public void testRemoveNonExistingGroup() throws SQLException {
Group group1 = new Group("group1");
- _groups.add(group1);
+ groups.add(group1);
checkGroupCount(1);
Group nonExistingGroup = new Group("group2");
nonExistingGroup.setPrimaryKey(new Long(1000));
nonExistingGroup.setPersistedVersion(1000);
- assertFalse(_groups.remove(nonExistingGroup));
- assertTrue(_groups.contains(group1));
- assertEquals(1, _groups.list().size());
+ assertFalse(groups.remove(nonExistingGroup));
+ assertTrue(groups.contains(group1));
+ assertEquals(1, groups.list().size());
checkGroupCount(1);
}
Group group1 = new Group("group1");
Group group2 = new Group("group2");
Group group3 = new Group("group3");
- assertTrue(_groups.add(group1));
- assertTrue(_groups.add(group2));
- assertTrue(_groups.add(group3));
+ assertTrue(groups.add(group1));
+ assertTrue(groups.add(group2));
+ assertTrue(groups.add(group3));
checkGroupExists(group1.getName());
checkGroupExists(group2.getName());
checkGroupExists(group3.getName());
- Set<Group> set = _groups.list();
+ Set<Group> set = groups.list();
assertTrue(set.contains(group1));
assertTrue(set.contains(group2));
assertTrue(set.contains(group3));
protected static final String PASSWORD = "abc123";
- private UserSet _users;
- private GroupSet _groups;
+ private UserSet users;
+ private GroupSet groups;
- private Group _group;
+ private Group group;
/**
* This method must be overriden in subclasses.
@Override
protected void setUp() throws Exception {
super.setUp();
- _users = createUserSet();
- _groups = createGroupSet();
- _group = new Group("group0");
- _groups.add(_group);
+ users = createUserSet();
+ groups = createGroupSet();
+ group = new Group("group0");
+ groups.add(group);
checkUserCount(0);
}
protected UserSet getUsers() {
- return _users;
+ return users;
}
protected GroupSet getGroups() {
- return _groups;
+ return groups;
}
protected Group createGroup(String aName) {
* @param aSize Expected number of users.
*/
protected void checkUserCount(int aSize) throws SQLException {
- assertEquals(aSize, _users.size());
+ assertEquals(aSize, users.size());
}
/**
*
*/
public void testAdd() throws SQLException, UserMgtException {
- User user = createUser("user1", PASSWORD, _group);
- assertTrue( _users.add(user) );
+ User user = createUser("user1", PASSWORD, group);
+ assertTrue( users.add(user) );
checkUserExists(user.getName());
checkUserCount(1);
- User user2 = _users.find("user1");
+ User user2 = users.find("user1");
assertNotNull(user2);
assertEquals(user.getName(), user2.getName());
- Set<User> set = _users.list();
+ Set<User> set = users.list();
assertEquals(1, set.size());
assertTrue(set.contains(user));
}
*
*/
public void testFindUnknownUser() throws SQLException, UserMgtException {
- User user1 = createUser("user1", PASSWORD, _group);
- User user2 = createUser("user2", PASSWORD, _group);
- _users.add(user1);
- _users.add(user2);
+ User user1 = createUser("user1", PASSWORD, group);
+ User user2 = createUser("user2", PASSWORD, group);
+ users.add(user1);
+ users.add(user2);
checkUserExists(user1.getName());
checkUserExists(user2.getName());
- assertNull( _users.find("user3") );
+ assertNull( users.find("user3") );
checkUserNotExists("user3");
}
* Adds duplicate user. Verifies that the existing user is left untouched.
*/
public void testAddDuplicateUser() throws SQLException, UserMgtException {
- User user1 = createUser("user1", PASSWORD, _group);
- _users.add(user1);
+ User user1 = createUser("user1", PASSWORD, group);
+ users.add(user1);
- assertEquals(1, _users.list().size());
- assertTrue(_users.contains(user1));
- user1 = createUser("user1", PASSWORD, _group);
- assertFalse(_users.add(user1));
- assertEquals(1, _users.list().size());
+ assertEquals(1, users.list().size());
+ assertTrue(users.contains(user1));
+ user1 = createUser("user1", PASSWORD, group);
+ assertFalse(users.add(user1));
+ assertEquals(1, users.list().size());
checkUserExists(user1.getName());
checkUserCount(1);
*
*/
public void testRemoveUser() throws SQLException, UserMgtException {
- User user1 = createUser("user1", PASSWORD, _group);
- _users.add(user1);
- assertTrue(_users.contains(user1));
+ User user1 = createUser("user1", PASSWORD, group);
+ users.add(user1);
+ assertTrue(users.contains(user1));
checkUserCount(1);
- assertTrue(_users.remove(user1));
- assertFalse(_users.contains(user1));
- assertNull(_users.find(user1.getName()));
- assertEquals(0, _users.list().size());
+ assertTrue(users.remove(user1));
+ assertFalse(users.contains(user1));
+ assertNull(users.find(user1.getName()));
+ assertEquals(0, users.list().size());
checkUserCount(0);
}
*
*/
public void testRemoveNonExistingUser() throws SQLException, UserMgtException {
- User user1 = createUser("user1", PASSWORD, _group);
- _users.add(user1);
+ User user1 = createUser("user1", PASSWORD, group);
+ users.add(user1);
checkUserCount(1);
- User nonExistingUser = createUser("user2", PASSWORD, _group);
+ User nonExistingUser = createUser("user2", PASSWORD, group);
nonExistingUser.setPrimaryKey(new Long(1000));
nonExistingUser.setPersistedVersion(10);
- assertFalse(_users.remove(nonExistingUser));
- assertTrue(_users.contains(user1));
- assertEquals(1, _users.list().size());
+ assertFalse(users.remove(nonExistingUser));
+ assertTrue(users.contains(user1));
+ assertEquals(1, users.list().size());
checkUserCount(1);
}
*
*/
public void testList() throws SQLException, UserMgtException {
- User user1 = createUser("user1", PASSWORD, _group);
- User user2 = createUser("user2", PASSWORD, _group);
- User user3 = createUser("user3", PASSWORD, _group);
- assertTrue(_users.add(user1));
- assertTrue(_users.add(user2));
- assertTrue(_users.add(user3));
+ User user1 = createUser("user1", PASSWORD, group);
+ User user2 = createUser("user2", PASSWORD, group);
+ User user3 = createUser("user3", PASSWORD, group);
+ assertTrue(users.add(user1));
+ assertTrue(users.add(user2));
+ assertTrue(users.add(user3));
checkUserExists(user1.getName());
checkUserExists(user2.getName());
checkUserExists(user3.getName());
- Set<User> set = _users.list();
+ Set<User> set = users.list();
assertTrue(set.contains(user1));
assertTrue(set.contains(user2));
assertTrue(set.contains(user3));
Group group1 = new Group("group1");
Group group2 = new Group("group2");
Group group3 = new Group("group3");
- _groups.add(group1);
- _groups.add(group2);
- _groups.add(group3);
+ groups.add(group1);
+ groups.add(group2);
+ groups.add(group3);
// user1 user2 user3
// group1 y
User user2 = createUser("user2", PASSWORD, group2);
user2.addGroup(group3);
User user3 = createUser("user3", PASSWORD, group3);
- _users.add(user1);
- _users.add(user2);
- _users.add(user3);
+ users.add(user1);
+ users.add(user2);
+ users.add(user3);
checkUserExists(user1.getName());
checkUserExists(user2.getName());
checkUserCount(3);
checkGroupCount(3+1); // also count the group that was created in the setUp().
- Set<User> list = _users.list(group1);
+ Set<User> list = users.list(group1);
assertTrue(list.contains(user1));
assertEquals(1, list.size());
- list = _users.list(group2);
+ list = users.list(group2);
assertTrue(list.contains(user1));
assertTrue(list.contains(user2));
assertEquals(2, list.size());
- list = _users.list(group3);
+ list = users.list(group3);
assertTrue(list.contains(user1));
assertTrue(list.contains(user2));
assertTrue(list.contains(user3));
private static final String GROUP2 = "runners";
- private UserAdministration _admin;
+ private UserAdministration admin;
/*
@Override
protected void setUp() throws Exception {
super.setUp();
- _admin = createAdmin();
+ admin = createAdmin();
}
protected UserAdministration createAdmin() {
* Constructs the admin, verify it contains no users and no groups.
*/
public void testConstruct() {
- assertEquals(0, _admin.getUsers().size());
- assertEquals(0, _admin.getGroups().size());
- assertEquals(0, _admin.getUserCount());
- assertEquals(0, _admin.getGroupCount());
+ assertEquals(0, admin.getUsers().size());
+ assertEquals(0, admin.getGroups().size());
+ assertEquals(0, admin.getUserCount());
+ assertEquals(0, admin.getGroupCount());
}
/**
*
*/
public void testCreateGroup() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
assertNotNull(group);
assertEquals(GROUP1, group.getName());
- Set<Group> groups = _admin.getGroups();
+ Set<Group> groups = admin.getGroups();
assertEquals(1, groups.size());
- assertEquals(1, _admin.getGroupCount());
+ assertEquals(1, admin.getGroupCount());
assertTrue(groups.contains(group));
}
private void createInvalidGroup(String aUsername) {
try {
- _admin.createGroup(aUsername);
+ admin.createGroup(aUsername);
fail();
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.INVALID_GROUPNAME, e
.getReason());
- assertEquals(0, _admin.getGroupCount());
+ assertEquals(0, admin.getGroupCount());
}
}
*
*/
public void testCreateDuplicateGroup() throws UserMgtException {
- _admin.createGroup(GROUP1);
+ admin.createGroup(GROUP1);
try {
- _admin.createGroup(GROUP1);
+ admin.createGroup(GROUP1);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.DUPLICATE_GROUP, e.getReason());
- assertEquals(1, _admin.getGroupCount());
+ assertEquals(1, admin.getGroupCount());
return;
}
fail();
*
*/
public void testCreateUser() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- User user = _admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
assertNotNull(user);
assertEquals(USER1, user.getName());
user.checkPassword(PASS1);
- Set<User> users = _admin.getUsers();
+ Set<User> users = admin.getUsers();
assertEquals(1, users.size());
- assertEquals(1, _admin.getUserCount());
+ assertEquals(1, admin.getUserCount());
assertTrue(users.contains(user));
}
private void createInvalidUser(String aUsername, Group aGroup) {
try {
- _admin.createUser(aUsername, "pass", aGroup);
+ admin.createUser(aUsername, "pass", aGroup);
fail();
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.INVALID_USERNAME, e
.getReason());
- assertEquals(0, _admin.getUserCount());
+ assertEquals(0, admin.getUserCount());
}
}
*
*/
public void testCreateInvalidUserName() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
createInvalidUser("", group);
createInvalidUser("0abc", group); // should not start with digits
createInvalidUser("a b", group); // should not contain spaces
*
*/
public void testCreateDuplicateUser() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- _admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ admin.createUser(USER1, PASS1, group);
try {
- _admin.createUser(USER1, PASS2, group);
+ admin.createUser(USER1, PASS2, group);
fail();
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.DUPLICATE_USER, e.getReason());
- assertEquals(1, _admin.getUserCount());
+ assertEquals(1, admin.getUserCount());
}
}
*
*/
public void testGetUser() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- User user = _admin.createUser(USER1, PASS1, group);
- User user2 = _admin.getUser(USER1);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
+ User user2 = admin.getUser(USER1);
assertTrue(user.equals(user2));
- assertNull(_admin.getUser(USER2));
+ assertNull(admin.getUser(USER2));
}
/**
*
*/
public void testGetGroup() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- Group group2 = _admin.getGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
+ Group group2 = admin.getGroup(GROUP1);
assertTrue(group.equals(group2));
- assertNull(_admin.getGroup(GROUP2));
+ assertNull(admin.getGroup(GROUP2));
}
/**
*/
public void testAddUserToGroup() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- User user = _admin.createUser(USER1, PASS1, group);
- Group group2 = _admin.createGroup(GROUP2);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
+ Group group2 = admin.createGroup(GROUP2);
assertTrue(user.isInGroup(group));
assertFalse(user.isInGroup(group2));
- _admin.addUserToGroup(user, group2);
+ admin.addUserToGroup(user, group2);
assertTrue(user.isInGroup(group));
assertTrue(user.isInGroup(group2));
- Set<User> users = _admin.getUsers(group2);
+ Set<User> users = admin.getUsers(group2);
assertNotNull(users);
assertEquals(1, users.size());
assertTrue(users.contains(user));
try {
- _admin.addUserToGroup(user, group);
+ admin.addUserToGroup(user, group);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.USER_ALREADY_IN_GROUP, e
.getReason());
*
*/
public void testAddUserToGroupUnknownUser() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
User user = createUser(USER1, PASS1, group);
try {
- _admin.addUserToGroup(user, group);
+ admin.addUserToGroup(user, group);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.UNKNOWN_USER, e.getReason());
return;
*
*/
public void testAddUserToGroupUnknownGroup() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- User user = _admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
Group group2 = new Group(GROUP2);
try {
- _admin.addUserToGroup(user, group2);
+ admin.addUserToGroup(user, group2);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.UNKNOWN_GROUP, e.getReason());
return;
* user not part of the group or if the user is only part of one group.
*/
public void testRemoveUserFromGroup() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
- User user = _admin.createUser(USER1, PASS1, group);
- Group group2 = _admin.createGroup(GROUP2);
- _admin.addUserToGroup(user, group2);
+ User user = admin.createUser(USER1, PASS1, group);
+ Group group2 = admin.createGroup(GROUP2);
+ admin.addUserToGroup(user, group2);
Set<Group> groups = user.getGroups();
assertEquals(2, groups.size());
assertTrue(groups.contains(group));
assertTrue(groups.contains(group2));
- _admin.removeUserFromGroup(user, group);
+ admin.removeUserFromGroup(user, group);
groups = user.getGroups();
assertEquals(1, groups.size());
assertTrue(groups.contains(group2));
*
*/
public void testRemoveUserFromGroupUnknownUser() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
User user = createUser(USER1, GROUP1, group);
try {
- _admin.removeUserFromGroup(user, group);
+ admin.removeUserFromGroup(user, group);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.UNKNOWN_USER, e.getReason());
}
*
*/
public void testRemoveUserFromGroupUnknownGroup() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- User user = _admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
Group group2 = new Group(GROUP2);
try {
- _admin.removeUserFromGroup(user, group2);
+ admin.removeUserFromGroup(user, group2);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.UNKNOWN_GROUP, e.getReason());
}
* Verifies that an exception is thrown.
*/
public void testRemoveUserFromGroupOnlyGroup() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- User user = _admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
try {
- _admin.removeUserFromGroup(user, group);
+ admin.removeUserFromGroup(user, group);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.USER_MUST_BE_IN_A_GROUP, e
.getReason());
*
*/
public void testGetUsersAndGroups() throws UserMgtException {
- Group group1 = _admin.createGroup(GROUP1);
- Group group2 = _admin.createGroup(GROUP2);
+ Group group1 = admin.createGroup(GROUP1);
+ Group group2 = admin.createGroup(GROUP2);
- User user1 = _admin.createUser(USER1, PASS1, group1);
- _admin.addUserToGroup(user1, group2);
- User user2 = _admin.createUser(USER2, PASS2, group2);
+ User user1 = admin.createUser(USER1, PASS1, group1);
+ admin.addUserToGroup(user1, group2);
+ User user2 = admin.createUser(USER2, PASS2, group2);
- Set<User> users = _admin.getUsers();
+ Set<User> users = admin.getUsers();
assertEquals(2, users.size());
assertTrue(users.contains(user1));
assertTrue(users.contains(user2));
- Set<Group> groups = _admin.getGroups();
+ Set<Group> groups = admin.getGroups();
assertEquals(2, groups.size());
assertTrue(groups.contains(group1));
assertTrue(groups.contains(group2));
*
*/
public void testRenameUser() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- User user1 = _admin.createUser(USER1, PASS1, group);
- _admin.renameUser(user1, USER2);
+ Group group = admin.createGroup(GROUP1);
+ User user1 = admin.createUser(USER1, PASS1, group);
+ admin.renameUser(user1, USER2);
assertEquals(USER2, user1.getName());
- assertEquals(user1, _admin.getUser(USER2));
+ assertEquals(user1, admin.getUser(USER2));
- _admin.createUser(USER1, PASS1, group);
+ admin.createUser(USER1, PASS1, group);
try {
- _admin.renameUser(user1, USER1);
+ admin.renameUser(user1, USER1);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.DUPLICATE_USER, e.getReason());
// do a trivial reanem
try {
- _admin.renameUser(user1, user1.getName());
+ admin.renameUser(user1, user1.getName());
} catch (UserMgtException e2) {
assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2
.getReason());
*
*/
public void testRenameUserInvalidUsername() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- User user1 = _admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ User user1 = admin.createUser(USER1, PASS1, group);
try {
- _admin.renameUser(user1, USER2);
+ admin.renameUser(user1, USER2);
} catch (UserMgtException e) {
assertEquals(e.getReason(), Reason.INVALID_USERNAME);
}
*
*/
public void testRenameGroup() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- _admin.renameGroup(group, GROUP2);
+ Group group = admin.createGroup(GROUP1);
+ admin.renameGroup(group, GROUP2);
assertEquals(GROUP2, group.getName());
- assertEquals(group, _admin.getGroup(GROUP2));
+ assertEquals(group, admin.getGroup(GROUP2));
- _admin.createGroup(GROUP1);
+ admin.createGroup(GROUP1);
try {
- _admin.renameGroup(group, GROUP1);
+ admin.renameGroup(group, GROUP1);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.DUPLICATE_GROUP, e.getReason());
// do a trivial reanem
try {
- _admin.renameGroup(group, group.getName());
+ admin.renameGroup(group, group.getName());
} catch (UserMgtException e2) {
assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2
.getReason());
*
*/
public void testRenameGroupInvalidGroupname() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
try {
- _admin.renameGroup(group, "a b");
+ admin.renameGroup(group, "a b");
} catch (UserMgtException e) {
assertEquals(e.getReason(), Reason.INVALID_GROUPNAME);
}
*
*/
public void testRemoveUser() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- User user = _admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
- assertEquals(1, _admin.getUserCount());
- _admin.removeUser(user);
- assertEquals(0, _admin.getUserCount());
+ assertEquals(1, admin.getUserCount());
+ admin.removeUser(user);
+ assertEquals(0, admin.getUserCount());
- _admin.createUser(USER1, PASS1, group);
- assertEquals(1, _admin.getUserCount());
+ admin.createUser(USER1, PASS1, group);
+ assertEquals(1, admin.getUserCount());
User user2 = createUser(USER2, PASS2, group);
try {
- _admin.removeUser(user2);
+ admin.removeUser(user2);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.UNKNOWN_USER, e.getReason());
}
*
*/
public void testRemoveGroup() throws UserMgtException {
- Group group1 = _admin.createGroup(GROUP1);
- assertEquals(1, _admin.getGroupCount());
- _admin.removeGroup(group1);
- assertEquals(0, _admin.getGroupCount());
- group1 = _admin.createGroup(GROUP1);
+ Group group1 = admin.createGroup(GROUP1);
+ assertEquals(1, admin.getGroupCount());
+ admin.removeGroup(group1);
+ assertEquals(0, admin.getGroupCount());
+ group1 = admin.createGroup(GROUP1);
- _admin.createUser(USER1, PASS1, group1);
+ admin.createUser(USER1, PASS1, group1);
try {
- _admin.removeGroup(group1);
+ admin.removeGroup(group1);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.GROUP_STILL_OCCUPIED, e
.getReason());
*
*/
public void testRemoveGroupUnknownGroup() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
Group group2 = new Group(GROUP2);
try {
- _admin.removeGroup(group2);
+ admin.removeGroup(group2);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.UNKNOWN_GROUP, e.getReason());
}
* @throws UserMgtException
*/
public void testChangePassword() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- User user = _admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
user.changePassword(PASS1, PASS2);
// retrieve the user and verifies the password hasn't changed.
- User user2 = _admin.getUser(USER1);
+ User user2 = admin.getUser(USER1);
try {
user2.checkPassword(PASS2);
fail(); // password should not have changed already.
}
// now notify the admin of the change in the user
- _admin.userModified(user);
+ admin.userModified(user);
- user2 = _admin.getUser(USER1);
+ user2 = admin.getUser(USER1);
user2.checkPassword(PASS2); // this time it should succeed.
}
*
*/
public void testPerformanceFindUserByName() throws UserMgtException {
- Group group = _admin.createGroup(GROUP1);
- _admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ admin.createUser(USER1, PASS1, group);
int n = 1000;
long time = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
- _admin.getUser(USER1);
+ admin.getUser(USER1);
}
LOGGER.info("Looked up a user " + n + " times in "
+ (float) (System.currentTimeMillis() - time) / 1000.0);
private static final String GROUP_QUERY = "select * from " + GROUP_TABLE + " where name = ?";
- private DefaultContainer _container;
- private Scope _scope;
+ private DefaultContainer container;
+ private Scope scope;
- private DatabaseTesterComponent _databaseTester;
- private GroupSet _groupSet;
+ private DatabaseTesterComponent databaseTester;
+ private GroupSet groupSet;
@Override
protected void setUp() throws Exception {
- _container = new UserMgtRepositoryTestContainer("top");
+ container = new UserMgtRepositoryTestContainer("top");
ObjectConfiguration config = new ObjectConfiguration(
HibernateGroupSetTest.class);
config.getSetterConfig().clear().add(
"setGroupSet").add("setDatabaseTester");
- _container.addComponent("testcase", this, config);
+ container.addComponent("testcase", this, config);
- _scope = _container.start();
+ scope = container.start();
- _databaseTester.cleanDatabase();
+ databaseTester.cleanDatabase();
super.setUp();
}
@Override
protected void tearDown() throws Exception {
- _container.stop(_scope);
+ container.stop(scope);
super.tearDown();
}
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
- _databaseTester = aDatabaseTester;
+ databaseTester = aDatabaseTester;
}
public void setGroupSet(GroupSet aGroupSet) {
- _groupSet = aGroupSet;
+ groupSet = aGroupSet;
}
/* (non-Javadoc)
*/
@Override
protected void checkGroupCount(int aSize) throws SQLException {
- _databaseTester.flush();
+ databaseTester.flush();
super.checkGroupCount(aSize);
- assertEquals(aSize, _databaseTester.getTableSize(GROUP_TABLE));
+ assertEquals(aSize, databaseTester.getTableSize(GROUP_TABLE));
}
/* (non-Javadoc)
*/
@Override
protected void checkGroupExists(final String aGroup) throws SQLException {
- _databaseTester.flush();
+ databaseTester.flush();
Map<String,Integer> result =
- _databaseTester.executeTransaction(new TestTransactionCallback() {
+ databaseTester.executeTransaction(new TestTransactionCallback() {
/* (non-Javadoc)
* @see org.wamblee.test.TestTransactionCallback#execute()
*/
@Override
public Map execute() throws Exception {
- ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup);
+ ResultSet result = databaseTester.executeQuery(GROUP_QUERY, aGroup);
Map<String,Integer> res = new HashMap<String,Integer>();
- res.put("result", _databaseTester.countResultSet(result));
+ res.put("result", databaseTester.countResultSet(result));
return res;
}
});
*/
@Override
protected void checkGroupNotExists(String aGroup) throws SQLException {
- _databaseTester.flush();
- ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup);
- assertEquals(0, _databaseTester.countResultSet(result));
+ databaseTester.flush();
+ ResultSet result = databaseTester.executeQuery(GROUP_QUERY, aGroup);
+ assertEquals(0, databaseTester.countResultSet(result));
}
/* (non-Javadoc)
*/
@Override
protected GroupSet createGroupSet() {
- return _groupSet;
+ return groupSet;
}
}
private static final Log LOG = LogFactory.getLog(HibernateUserAdministrationTest.class);
- private DefaultContainer _container;
- private Scope _scope;
+ private DefaultContainer container;
+ private Scope scope;
- private DatabaseTesterComponent _databaseTester;
- private EhCache<Serializable, Serializable> _userCache;
- private UserAdministration _userAdmin;
+ private DatabaseTesterComponent databaseTester;
+ private EhCache<Serializable, Serializable> userCache;
+ private UserAdministration userAdmin;
/* (non-Javadoc)
@Override
protected void setUp() throws Exception {
- _container = new DefaultContainer("top");
- DatabaseComponentFactory.addDatabaseConfig(_container);
- _container.addComponent(new DatasourceComponent("datasource"));
- _container.addComponent(new UserAdministrationComponent("admin", true));
+ container = new DefaultContainer("top");
+ DatabaseComponentFactory.addDatabaseConfig(container);
+ container.addComponent(new DatasourceComponent("datasource"));
+ container.addComponent(new UserAdministrationComponent("admin", true));
ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class);
dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
- _container.addComponent("databaseTester", dbtesterConfig);
+ container.addComponent("databaseTester", dbtesterConfig);
ObjectConfiguration config = new ObjectConfiguration(
HibernateUserAdministrationTest.class);
config.getSetterConfig().clear().add(
"setUserCache").add("setDatabaseTester").add("setUserAdmin");
- _container.addComponent("testcase", this, config);
+ container.addComponent("testcase", this, config);
- _scope = _container.start();
+ scope = container.start();
- _databaseTester.cleanDatabase();
+ databaseTester.cleanDatabase();
super.setUp();
clearUserCache();
}
public void setUserCache(EhCache<Serializable, Serializable> aUserCache) {
- _userCache = aUserCache;
+ userCache = aUserCache;
}
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
- _databaseTester = aDatabaseTester;
+ databaseTester = aDatabaseTester;
}
public void setUserAdmin(UserAdministration aUserAdmin) {
- _userAdmin = aUserAdmin;
+ userAdmin = aUserAdmin;
}
@Override
protected void tearDown() throws Exception {
- _container.stop(_scope);
+ container.stop(scope);
super.tearDown();
}
*/
@Override
protected UserAdministration createAdmin() {
- return _userAdmin;
+ return userAdmin;
}
public void testAllTestsInASeparateTransaction() throws SQLException {
Method[] methods = UserAdministrationImplTest.class.getMethods();
for (final Method method : methods) {
if (method.getName().startsWith("test")) {
- _databaseTester.cleanDatabase();
+ databaseTester.cleanDatabase();
clearUserCache();
- _databaseTester.executeTransaction(new TestTransactionCallbackWithoutResult() {
+ databaseTester.executeTransaction(new TestTransactionCallbackWithoutResult() {
public void execute() throws Exception {
LOG.info("Running test " + method.getName());
try {
*
*/
private void clearUserCache() {
- _userCache.clear();
+ userCache.clear();
}
}
private static final String GROUP_QUERY = "select * from " + GROUP_TABLE
+ " where name = ?";
- private DefaultContainer _container;
- private Scope _scope;
+ private DefaultContainer container;
+ private Scope scope;
- private UserSet _userset;
- private GroupSet _groupset;
- private EhCache<Serializable, Serializable> _userCache;
- private DatabaseTesterComponent _databaseTester;
+ private UserSet userset;
+ private GroupSet groupset;
+ private EhCache<Serializable, Serializable> userCache;
+ private DatabaseTesterComponent databaseTester;
/*
* (non-Javadoc)
@Override
protected void setUp() throws Exception {
- _container = new UserMgtRepositoryTestContainer("top");
+ container = new UserMgtRepositoryTestContainer("top");
ObjectConfiguration config = new ObjectConfiguration(
HibernateUserSetTest.class);
config.getSetterConfig().clear().add("setUserset").add(
"setGroupset").add("setDatabaseTester").add("setUserCache");
- _container.addComponent("testcase", this, config);
+ container.addComponent("testcase", this, config);
- _scope = _container.start();
+ scope = container.start();
clearUserCache();
- _databaseTester.cleanDatabase();
+ databaseTester.cleanDatabase();
super.setUp();
}
public void setUserset(UserSet aUserset) {
- _userset = aUserset;
+ userset = aUserset;
}
public void setGroupset(GroupSet aGroupset) {
- _groupset = aGroupset;
+ groupset = aGroupset;
}
public void setUserCache(EhCache<Serializable, Serializable> aUserCache) {
- _userCache = aUserCache;
+ userCache = aUserCache;
}
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
- _databaseTester = aDatabaseTester;
+ databaseTester = aDatabaseTester;
}
@Override
protected void tearDown() throws Exception {
- _container.stop(_scope);
+ container.stop(scope);
super.tearDown();
}
* Clears the user cache.
*/
private void clearUserCache() {
- _userCache.clear();
+ userCache.clear();
}
/*
*/
@Override
protected void checkUserCount(int aSize) throws SQLException {
- _databaseTester.flush();
+ databaseTester.flush();
super.checkUserCount(aSize);
- assertEquals(aSize, _databaseTester.getTableSize(USER_TABLE));
+ assertEquals(aSize, databaseTester.getTableSize(USER_TABLE));
}
/*
*/
@Override
protected void checkUserExists(String aUser) throws SQLException {
- _databaseTester.flush();
- ResultSet result = _databaseTester.executeQuery(USER_QUERY, aUser);
- assertEquals(1, _databaseTester.countResultSet(result));
+ databaseTester.flush();
+ ResultSet result = databaseTester.executeQuery(USER_QUERY, aUser);
+ assertEquals(1, databaseTester.countResultSet(result));
}
/*
*/
@Override
protected void checkUserNotExists(String aUser) throws SQLException {
- _databaseTester.flush();
- ResultSet result = _databaseTester.executeQuery(USER_QUERY, aUser);
- assertEquals(0, _databaseTester.countResultSet(result));
+ databaseTester.flush();
+ ResultSet result = databaseTester.executeQuery(USER_QUERY, aUser);
+ assertEquals(0, databaseTester.countResultSet(result));
}
/*
*/
@Override
protected void checkGroupCount(int aSize) throws SQLException {
- _databaseTester.flush();
- assertEquals(aSize, _databaseTester.getTableSize(GROUP_TABLE));
+ databaseTester.flush();
+ assertEquals(aSize, databaseTester.getTableSize(GROUP_TABLE));
}
/*
*/
@Override
protected void checkGroupExists(String aGroup) throws SQLException {
- _databaseTester.flush();
+ databaseTester.flush();
- ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup);
- assertEquals(1, _databaseTester.countResultSet(result));
+ ResultSet result = databaseTester.executeQuery(GROUP_QUERY, aGroup);
+ assertEquals(1, databaseTester.countResultSet(result));
}
/*
*/
@Override
protected void checkGroupNotExists(String aGroup) throws SQLException {
- _databaseTester.flush();
- ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup);
- assertEquals(0, _databaseTester.countResultSet(result));
+ databaseTester.flush();
+ ResultSet result = databaseTester.executeQuery(GROUP_QUERY, aGroup);
+ assertEquals(0, databaseTester.countResultSet(result));
}
/*
*/
@Override
protected UserSet createUserSet() {
- return _userset;
+ return userset;
}
/*
*/
@Override
protected GroupSet createGroupSet() {
- return _groupset;
+ return groupset;
}
/**
* group2.
*/
public void testVerifyAddRemove() throws SQLException, UserMgtException {
- _databaseTester.cleanDatabase(); // just to be sure.
+ databaseTester.cleanDatabase(); // just to be sure.
GroupSet groups = getGroups();
assertEquals(0, groups.size());
Group group1 = createGroup("group1");
/**
* Cache to use.
*/
- private Cache<KeyType, ValueType> _cache;
+ private Cache<KeyType, ValueType> cache;
/**
* Key of the object in the cache.
*/
- private KeyType _objectKey;
+ private KeyType objectKey;
/**
* Computation used to obtain the object if it is not found in the cache.
*/
- private Computation<KeyType, ValueType> _computation;
+ private Computation<KeyType, ValueType> computation;
/**
* Constructs the cached object.
*/
public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
Computation<KeyType, ValueType> aComputation) {
- _cache = aCache;
- _objectKey = aObjectKey;
- _computation = aComputation;
+ cache = aCache;
+ objectKey = aObjectKey;
+ computation = aComputation;
}
/**
* @return Object.
*/
public ValueType get() {
- ValueType object = (ValueType) _cache.get(_objectKey); // the used
+ ValueType object = (ValueType) cache.get(objectKey); // the used
// cache is
// thread safe.
if (object == null) {
// be
// recomputed.
synchronized (this) {
- object = (ValueType) _cache.get(_objectKey);
+ object = (ValueType) cache.get(objectKey);
if (object == null) {
// No other thread did a recomputation so we must do this
// now.
- LOGGER.debug("Refreshing cache for '" + _objectKey + "'");
- object = _computation.getObject(_objectKey);
- _cache.put(_objectKey, object);
+ LOGGER.debug("Refreshing cache for '" + objectKey + "'");
+ object = computation.getObject(objectKey);
+ cache.put(objectKey, object);
}
}
}
*
*/
public void invalidate() {
- _cache.remove(_objectKey);
+ cache.remove(objectKey);
}
/**
* @return Cache.
*/
public Cache getCache() {
- return _cache;
+ return cache;
}
}
/**
* EH Cache manager.
*/
- private CacheManager _manager;
+ private CacheManager manager;
/**
* EH cache.
*/
- private Cache _cache;
+ private Cache cache;
/**
* Constructs a cache based on EHCache.
throws IOException, CacheException {
InputStream is = aResource.getInputStream();
try {
- _manager = new CacheManager(is);
- _cache = _manager.getCache(aCacheName);
- if (_cache == null) {
+ manager = new CacheManager(is);
+ cache = manager.getCache(aCacheName);
+ if (cache == null) {
LOGGER.warn("Creating cache '" + aCacheName
+ "' because it is not configured");
- _manager.addCache(aCacheName);
- _cache = _manager.getCache(aCacheName);
+ manager.addCache(aCacheName);
+ cache = manager.getCache(aCacheName);
}
- assert _cache != null;
+ assert cache != null;
} finally {
is.close();
}
* @see org.wamblee.cache.Cache#put(KeyType, ValueType)
*/
public void put(KeyType aKey, ValueType aValue) {
- _cache.put(new Element(aKey, aValue));
+ cache.put(new Element(aKey, aValue));
}
/*
*/
public ValueType get(KeyType aKey) {
try {
- Element element = _cache.get(aKey);
+ Element element = cache.get(aKey);
if (element == null) {
return null;
}
* @see org.wamblee.cache.Cache#remove(KeyType)
*/
public void remove(KeyType aKey) {
- _cache.remove(aKey);
+ cache.remove(aKey);
}
/*
* @see org.wamblee.cache.Cache#clear()
*/
public void clear() {
- _cache.removeAll();
+ cache.removeAll();
}
}
/**
* Cached entries.
*/
- private HashMap<KeyType, ValueType> _map;
+ private HashMap<KeyType, ValueType> map;
/**
* Constructs the cache.
*
*/
public ForeverCache() {
- _map = new HashMap<KeyType, ValueType>();
+ map = new HashMap<KeyType, ValueType>();
}
/*
* @see org.wamblee.cache.Cache#put(KeyType, ValueType)
*/
public synchronized void put(KeyType aKey, ValueType aValue) {
- _map.put(aKey, aValue);
+ map.put(aKey, aValue);
}
/*
* @see org.wamblee.cache.Cache#get(KeyType)
*/
public synchronized ValueType get(KeyType aKey) {
- return _map.get(aKey);
+ return map.get(aKey);
}
/*
* @see org.wamblee.cache.Cache#remove(KeyType)
*/
public synchronized void remove(KeyType aKey) {
- _map.remove(aKey);
+ map.remove(aKey);
}
/*
* @see org.wamblee.cache.Cache#clear()
*/
public synchronized void clear() {
- _map.clear();
+ map.clear();
}
}
/**
* Reentrant lock to use.
*/
- private ReentrantLock _lock;
+ private ReentrantLock lock;
/**
* In-memory lock.
*/
public JvmLock() {
- _lock = new ReentrantLock(true);
+ lock = new ReentrantLock(true);
}
/* (non-Javadoc)
* @see org.wamblee.concurrency.Lock#acquire()
*/
public void acquire() {
- _lock.lock();
+ lock.lock();
}
/* (non-Javadoc)
* @see org.wamblee.concurrency.Lock#release()
*/
public void release() {
- _lock.unlock();
+ lock.unlock();
}
}
* already been acquired before it is release. This check adds robustness
* to the application.
*/
- private HashSet<Thread> _readers;
+ private HashSet<Thread> readers;
/**
* The thread that has acquired the lock for writing or null if no such
* thread exists currently.
*/
- private Thread _writer;
+ private Thread writer;
/**
* Constructs read-write lock.
*/
public ReadWriteLock() {
- _readers = new HashSet<Thread>();
- _writer = null;
+ readers = new HashSet<Thread>();
+ writer = null;
}
/**
* already acquired.
*/
public synchronized void acquireRead() {
- if (_readers.contains(Thread.currentThread())) {
+ if (readers.contains(Thread.currentThread())) {
throw new IllegalStateException(
"Read lock already acquired by current thread: "
+ Thread.currentThread());
}
- if (_writer == Thread.currentThread()) {
+ if (writer == Thread.currentThread()) {
throw new IllegalStateException(
"Trying to acquire the read lock while already holding a write lock: "
+ Thread.currentThread());
}
- while (_writer != null) {
+ while (writer != null) {
try {
wait();
} catch (InterruptedException e) {
}
}
- _readers.add(Thread.currentThread());
+ readers.add(Thread.currentThread());
}
/**
* this thread.
*/
public synchronized void releaseRead() {
- if (!_readers.remove(Thread.currentThread())) {
+ if (!readers.remove(Thread.currentThread())) {
throw new IllegalStateException(
"Cannot release read lock because current thread has not acquired it.");
}
- if (_readers.size() == 0) {
+ if (readers.size() == 0) {
notifyAll();
}
}
* already acquired.
*/
public synchronized void acquireWrite() {
- if (_writer == Thread.currentThread()) {
+ if (writer == Thread.currentThread()) {
throw new IllegalStateException(
"Trying to acquire a write lock while already holding the write lock: "
+ Thread.currentThread());
}
- if (_readers.contains(Thread.currentThread())) {
+ if (readers.contains(Thread.currentThread())) {
throw new IllegalStateException(
"Trying to acquire a write lock while already holding the read lock: "
+ Thread.currentThread());
// wait until there are no more writers and no more
// readers
- while ((_writer != null) || (_readers.size() > 0)) {
+ while ((writer != null) || (readers.size() > 0)) {
try {
wait();
} catch (InterruptedException e) {
}
}
- _writer = Thread.currentThread();
+ writer = Thread.currentThread();
// notification not necessary since all writers and
// readers are now blocked by this thread.
* @throws IllegalStateException Thrown when the lock was not acquired.
*/
public synchronized void releaseWrite() {
- if (_writer != Thread.currentThread()) {
+ if (writer != Thread.currentThread()) {
throw new IllegalStateException(
"Cannot release write lock because it was not acquired. ");
}
- _writer = null;
+ writer = null;
notifyAll();
}
}
*/
public class AndCondition<T> implements Condition<T> {
- private List<Condition<T>> _conditions;
+ private List<Condition<T>> conditions;
/**
* Constructs the condition.
* Second condition.
*/
public AndCondition(Condition<T> aCondition1, Condition<T> aCondition2) {
- _conditions = new ArrayList<Condition<T>>();
- _conditions.add(aCondition1);
- _conditions.add(aCondition2);
+ conditions = new ArrayList<Condition<T>>();
+ conditions.add(aCondition1);
+ conditions.add(aCondition2);
}
/**
* List of conditions to use in the logical and.
*/
public AndCondition(List<Condition<T>> aConditions) {
- _conditions = aConditions;
+ conditions = aConditions;
}
/*
* @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program)
*/
public boolean matches(T aObject) {
- for (Condition<T> condition : _conditions) {
+ for (Condition<T> condition : conditions) {
if (!condition.matches(aObject)) {
return false;
}
*/
public class FixedCondition<T> implements Condition<T> {
- private boolean _value;
+ private boolean value;
/**
* Constructs the condition.
* @param aValue Fixed value of the condition.
*/
public FixedCondition(boolean aValue) {
- _value = aValue;
+ value = aValue;
}
/* (non-Javadoc)
* @see org.wamblee.conditions.Condition#matches(T)
*/
public boolean matches(T aObject) {
- return _value;
+ return value;
}
}
*/
public class OrCondition<T> implements Condition<T> {
- private List<Condition<T>> _conditions;
+ private List<Condition<T>> conditions;
/**
* Constructs the condition.
* Second condition.
*/
public OrCondition(Condition<T> aCondition1, Condition<T> aCondition2) {
- _conditions = new ArrayList<Condition<T>>();
- _conditions.add(aCondition1);
- _conditions.add(aCondition2);
+ conditions = new ArrayList<Condition<T>>();
+ conditions.add(aCondition1);
+ conditions.add(aCondition2);
}
/**
* List of conditions to use in the logical or.
*/
public OrCondition(List<Condition<T>> aConditions) {
- _conditions = aConditions;
+ conditions = aConditions;
}
/*
* @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program)
*/
public boolean matches(T aObject) {
- for (Condition<T> condition : _conditions) {
+ for (Condition<T> condition : conditions) {
if (condition.matches(aObject)) {
return true;
}
/**
* Property name.
*/
- private String _property;
+ private String property;
/**
* Regular expression.
*/
- private Pattern _regex;
+ private Pattern regex;
/**
* Whether or not to convert the value to lowercase before matching.
*/
- private boolean _tolower;
+ private boolean tolower;
/**
* Constructs the condition.
* @param aTolower Whether or not to convert the value to lowercase before matching.
*/
public PropertyRegexCondition(String aProperty, String aRegex, boolean aTolower) {
- _property = aProperty;
- _regex = Pattern.compile(aRegex);
- _tolower = aTolower;
+ property = aProperty;
+ regex = Pattern.compile(aRegex);
+ tolower = aTolower;
}
/* (non-Javadoc)
*/
public boolean matches(T aObject) {
try {
- String value = PropertyUtils.getProperty(aObject, _property) + "";
- if ( _tolower ) {
+ String value = PropertyUtils.getProperty(aObject, property) + "";
+ if ( tolower ) {
value = value.toLowerCase();
}
- Matcher matcher = _regex.matcher(value);
+ Matcher matcher = regex.matcher(value);
return matcher.matches();
} catch (IllegalAccessException e) {
throw new RuntimeException(e.getMessage(), e);
*/
public class Pair<T, U> {
- private T _t;
+ private T t;
- private U _u;
+ private U u;
/**
* Constructs the pair.
* Second object.
*/
public Pair(T aT, U aU) {
- _t = aT;
- _u = aU;
+ t = aT;
+ u = aU;
}
/**
* Pair to copy.
*/
public Pair(Pair<T, U> aPair) {
- _t = aPair._t;
- _u = aPair._u;
+ t = aPair.t;
+ u = aPair.u;
}
/**
* @return First object.
*/
public T getFirst() {
- return _t;
+ return t;
}
/**
* @return Second object.
*/
public U getSecond() {
- return _u;
+ return u;
}
}
/**
* Resource name.
*/
- private String _resource;
+ private String resource;
/**
* Construct the class path resource.
* Resource
*/
public ClassPathResource(String aResource) {
- _resource = aResource;
+ resource = aResource;
}
/*
*/
public InputStream getInputStream() throws IOException {
InputStream stream = Thread.currentThread().getContextClassLoader()
- .getResourceAsStream(_resource);
+ .getResourceAsStream(resource);
if (stream == null) {
- throw new IOException("Class path resource '" + _resource
+ throw new IOException("Class path resource '" + resource
+ "' not found.");
}
return stream;
* @see java.lang.Object#toString()
*/
public String toString() {
- return "ClassPathResource(" + _resource + ")";
+ return "ClassPathResource(" + resource + ")";
}
}
void fileDeleted(File aFile);
};
- private File _directory;
- private FileFilter _filter;
- private Listener _listener;
- private Map<File, Date> _contents;
+ private File directory;
+ private FileFilter filter;
+ private Listener listener;
+ private Map<File, Date> contents;
public DirectoryMonitor(File aDirectory, FileFilter aFilefilter,
Listener aListener) {
- _directory = aDirectory;
- if (!_directory.isDirectory()) {
- throw new IllegalArgumentException("Directory '" + _directory
+ directory = aDirectory;
+ if (!directory.isDirectory()) {
+ throw new IllegalArgumentException("Directory '" + directory
+ "' does not exist");
}
- _filter = aFilefilter;
- _listener = aListener;
- _contents = new HashMap<File, Date>();
+ filter = aFilefilter;
+ listener = aListener;
+ contents = new HashMap<File, Date>();
}
/**
* the next call to this method will invoked the listeners again for the same changes.
*/
public void poll() {
- LOG.debug("Polling " + _directory);
+ LOG.debug("Polling " + directory);
Map<File, Date> newContents = new HashMap<File, Date>();
- File[] files = _directory.listFiles(_filter);
+ File[] files = directory.listFiles(filter);
// Check deleted files.
- Set<File> deletedFiles = new HashSet<File>(_contents.keySet());
+ Set<File> deletedFiles = new HashSet<File>(contents.keySet());
for (File file : files) {
if (file.isFile()) {
- if (_contents.containsKey(file)) {
+ if (contents.containsKey(file)) {
deletedFiles.remove(file);
}
}
}
for (File file : deletedFiles) {
- _listener.fileDeleted(file);
+ listener.fileDeleted(file);
}
for (File file : files) {
if (file.isFile()) {
- if (_contents.containsKey(file)) {
- Date oldDate = _contents.get(file);
+ if (contents.containsKey(file)) {
+ Date oldDate = contents.get(file);
if (file.lastModified() != oldDate.getTime()) {
- _listener.fileChanged(file);
+ listener.fileChanged(file);
} else {
// No change.
}
newContents.put(file, new Date(file.lastModified()));
} else {
- _listener.fileCreated(file);
+ listener.fileCreated(file);
newContents.put(file, new Date(file.lastModified()));
}
}
}
- _contents = newContents;
+ contents = newContents;
}
}
/**
* File to read.
*/
- private File _file;
+ private File file;
/**
* Constructs the resource.
* File to read.
*/
public FileResource(File aFile) {
- _file = aFile;
+ file = aFile;
}
/*
* @see org.wamblee.io.InputResource#getInputStream()
*/
public InputStream getInputStream() throws IOException {
- return new BufferedInputStream(new FileInputStream(_file));
+ return new BufferedInputStream(new FileInputStream(file));
}
}
private static final Log LOG = LogFactory.getLog(SimpleProcess.class);
- private File _directory;
+ private File directory;
- private String[] _cmd;
+ private String[] cmd;
- private String _stdout;
- private String _stderr;
+ private String stdout;
+ private String stderr;
public SimpleProcess(File aDirectory, String[] aCmd) {
- _directory = aDirectory;
- _cmd = aCmd;
+ directory = aDirectory;
+ cmd = aCmd;
}
/**
* @return the stdout
*/
public String getStdout() {
- return _stdout;
+ return stdout;
}
/**
* @return the stderr
*/
public String getStderr() {
- return _stderr;
+ return stderr;
}
/**
private int runImpl() throws IOException {
try {
String fullcmd = "";
- for (String part: _cmd) {
+ for (String part: cmd) {
fullcmd += " " + part;
}
- LOG.debug("Executing '" + fullcmd + "' in directory '" + _directory
+ LOG.debug("Executing '" + fullcmd + "' in directory '" + directory
+ "'");
- java.lang.Process proc = Runtime.getRuntime().exec(_cmd, null, _directory);
+ java.lang.Process proc = Runtime.getRuntime().exec(cmd, null, directory);
// Read standard output and error in separate threads to avoid
// deadlock.
- StringWriter stdout = new StringWriter();
- StringWriter stderr = new StringWriter();
+ StringWriter myStdout = new StringWriter();
+ StringWriter myStderr = new StringWriter();
Thread stdoutReader = readAndLogStream("STDOUT> ", proc
- .getInputStream(), stdout);
+ .getInputStream(), myStdout);
Thread stderrReader = readAndLogStream("STDERR> ", proc
- .getErrorStream(), stderr);
+ .getErrorStream(), myStderr);
try {
proc.waitFor();
waitForReader(stdoutReader);
waitForReader(stderrReader);
- _stdout = stdout.toString();
- _stderr = stderr.toString();
+ stdout = myStdout.toString();
+ stderr = myStderr.toString();
if (proc.exitValue() != 0) {
LOG.warn("Exit value was non-zero: " + this);
@Override
public String toString() {
String fullcmd = "";
- for (String part: _cmd) {
+ for (String part: cmd) {
fullcmd += part + " ";
}
- return "process(dir = '" + _directory + "', cmd = '" + fullcmd + "')";
+ return "process(dir = '" + directory + "', cmd = '" + fullcmd + "')";
}
}
/**
* Input stream to read.
*/
- private InputStream _stream;
+ private InputStream stream;
/**
* Constructs a resource.
* Input stream to read.
*/
public StreamResource(InputStream aStream) {
- _stream = aStream;
+ stream = aStream;
}
/*
* @see InputResource#getInputStream()
*/
public InputStream getInputStream() throws IOException {
- return _stream;
+ return stream;
}
}
/**
* Observable.
*/
- private ObservableType _observable;
+ private ObservableType observable;
/**
* Used to notify observers.
*/
- private ObserverNotifier<ObservableType, Event> _notifier;
+ private ObserverNotifier<ObservableType, Event> notifier;
/**
* Map of subscription to observer.
*/
- private Map<Long, Observer<ObservableType, Event>> _observers;
+ private Map<Long, Observer<ObservableType, Event>> observers;
/**
* Counter for subscriptions. Holds the next subscription.
*/
- private long _counter;
+ private long counter;
/**
* Constructs the observable.
*/
public Observable(ObservableType aObservable,
ObserverNotifier<ObservableType, Event> aNotifier) {
- _observable = aObservable;
- _notifier = aNotifier;
- _observers = new TreeMap<Long, Observer<ObservableType, Event>>();
- _counter = 0;
+ observable = aObservable;
+ notifier = aNotifier;
+ observers = new TreeMap<Long, Observer<ObservableType, Event>>();
+ counter = 0;
}
/**
* @return Event Event to send.
*/
public synchronized long subscribe(Observer<ObservableType, Event> aObserver) {
- long subscription = _counter++; // integer rage is so large it will
+ long subscription = counter++; // integer rage is so large it will
// never roll over.
- _observers.put(subscription, aObserver);
+ observers.put(subscription, aObserver);
return subscription;
}
* In case the subscription is not known.
*/
public synchronized void unsubscribe(long aSubscription) {
- Object obj = _observers.remove(aSubscription);
+ Object obj = observers.remove(aSubscription);
if (obj == null) {
throw new IllegalArgumentException("Subscription '" + aSubscription
+ "'");
* @return Number of subscribed observers.
*/
public int getObserverCount() {
- return _observers.size();
+ return observers.size();
}
/**
// Make sure we do the notification while not holding the lock to avoid
// potential deadlock
// situations.
- List<Observer<ObservableType, Event>> observers = new ArrayList<Observer<ObservableType, Event>>();
+ List<Observer<ObservableType, Event>> myObservers = new ArrayList<Observer<ObservableType, Event>>();
synchronized (this) {
- observers.addAll(_observers.values());
+ myObservers.addAll(observers.values());
}
- for (Observer<ObservableType, Event> observer : observers) {
- _notifier.update(observer, _observable, aEvent);
+ for (Observer<ObservableType, Event> observer : myObservers) {
+ notifier.update(observer, observable, aEvent);
}
}
*/
@Override
protected void finalize() throws Throwable {
- if (_observers.size() > 0) {
+ if (observers.size() > 0) {
LOGGER
.error("Still observers registered at finalization of observer!");
- for (Observer observer : _observers.values()) {
+ for (Observer observer : observers.values()) {
LOGGER.error(" observer: " + observer);
}
}
/**
* Primary key.
*/
- private Serializable _primaryKey;
+ private Serializable primaryKey;
/**
* Version.
*/
- private int _version;
+ private int version;
/**
* Constructs the object.
*
*/
protected AbstractPersistent() {
- _primaryKey = null;
- _version = -1;
+ primaryKey = null;
+ version = -1;
}
/**
* @param aPersistent Object to copy.
*/
protected AbstractPersistent(AbstractPersistent aPersistent) {
- _primaryKey = aPersistent._primaryKey;
- _version = aPersistent._version;
+ primaryKey = aPersistent.primaryKey;
+ version = aPersistent.version;
}
/* (non-Javadoc)
* @see org.wamblee.persistence.Persistent#getPrimaryKey()
*/
public Serializable getPrimaryKey() {
- return _primaryKey;
+ return primaryKey;
}
/* (non-Javadoc)
* @see org.wamblee.persistence.Persistent#setPrimaryKey(java.io.Serializable)
*/
public void setPrimaryKey(Serializable aKey) {
- _primaryKey = aKey;
+ primaryKey = aKey;
}
/* (non-Javadoc)
* @see org.wamblee.persistence.Persistent#getPersistedVersion()
*/
public int getPersistedVersion() {
- return _version;
+ return version;
}
/* (non-Javadoc)
* @see org.wamblee.persistence.Persistent#setPersistedVersion(int)
*/
public void setPersistedVersion(int aVersion) {
- _version = aVersion;
+ version = aVersion;
}
}
*/
public class XslTransformer {
- private TransformerFactory _factory;
+ private TransformerFactory factory;
/**
* Constructs the URL resolver.
* URI resolver to use.
*/
public XslTransformer(URIResolver aResolver) {
- _factory = TransformerFactory.newInstance();
- _factory.setURIResolver(aResolver);
+ factory = TransformerFactory.newInstance();
+ factory.setURIResolver(aResolver);
}
/**
*
*/
public XslTransformer() {
- _factory = TransformerFactory.newInstance();
+ factory = TransformerFactory.newInstance();
}
/**
* @throws TransformerException In case the XSLT cannot be found.
*/
public Source resolve(String aXslt) throws TransformerException {
- URIResolver resolver = _factory.getURIResolver();
+ URIResolver resolver = factory.getURIResolver();
if (resolver == null) {
if (new File(aXslt).canRead()) {
try {
public void transform(Source aSource, Result aResult, Source aXslt)
throws IOException, TransformerException {
try {
- Transformer transformer = _factory.newTransformer(aXslt);
+ Transformer transformer = factory.newTransformer(aXslt);
transformer.transform(aSource, aResult);
} catch (TransformerConfigurationException e) {
throw new TransformerException(
private static final int OBJECT_KEY = 10;
- private CachedObject.Computation<Integer,Integer> _computation;
- private int _ncomputations;
+ private CachedObject.Computation<Integer,Integer> computation;
+ private int ncomputations;
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
@Override
protected void setUp() throws Exception {
super.setUp();
- _computation = new CachedObject.Computation<Integer,Integer>() {
+ computation = new CachedObject.Computation<Integer,Integer>() {
public Integer getObject(Integer aObjectKey) {
- _ncomputations++;
+ ncomputations++;
return compute(aObjectKey);
};
};
- _ncomputations = 0;
+ ncomputations = 0;
}
private int compute(int aValue) {
}
private CachedObject<Integer, Integer> createCached(Cache<Integer,Integer> aCache) {
- return new CachedObject<Integer, Integer>(aCache, OBJECT_KEY, _computation);
+ return new CachedObject<Integer, Integer>(aCache, OBJECT_KEY, computation);
}
/**
CachedObject<Integer, Integer> cached = createCached(new ZeroCache<Integer,Integer>());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, _ncomputations);
+ assertEquals(1, ncomputations);
}
public void testInvalidateCache() {
CachedObject<Integer, Integer> cached = createCached(new ForeverCache<Integer,Integer>());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, _ncomputations);
+ assertEquals(1, ncomputations);
cached.invalidate();
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(2, _ncomputations);
+ assertEquals(2, ncomputations);
}
public void testBehaviorEhCache() throws CacheException, IOException {
assertTrue( cache == cached.getCache());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, _ncomputations);
+ assertEquals(1, ncomputations);
// The value must still be cached.
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, _ncomputations);
+ assertEquals(1, ncomputations);
// Cache expiry.
TimingUtils.sleep(6000);
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(2, _ncomputations);
+ assertEquals(2, ncomputations);
// Should still be cached now.
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(2, _ncomputations);
+ assertEquals(2, ncomputations);
// explicit invalidation.
cached.invalidate();
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(3, _ncomputations);
+ assertEquals(3, ncomputations);
}
assertTrue( cache == cached.getCache());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, _ncomputations);
+ assertEquals(1, ncomputations);
// The value must still be cached.
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, _ncomputations);
+ assertEquals(1, ncomputations);
// Cache expiry.
TimingUtils.sleep(6000);
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(2, _ncomputations);
+ assertEquals(2, ncomputations);
// Should still be cached now.
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(2, _ncomputations);
+ assertEquals(2, ncomputations);
}
CachedObject<Integer, Integer> cached = createCached(new ForeverCache<Integer,Integer>());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, _ncomputations);
+ assertEquals(1, ncomputations);
for (int ncomp = 2; ncomp <= 100; ncomp++) {
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, _ncomputations);
+ assertEquals(1, ncomputations);
}
}
CachedObject<Integer, Integer> cached = createCached(new ZeroCache<Integer,Integer>());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, _ncomputations);
+ assertEquals(1, ncomputations);
for (int ncomp = 2; ncomp <= 100; ncomp++) {
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(ncomp, _ncomputations);
+ assertEquals(ncomp, ncomputations);
}
cached.invalidate();
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(101, _ncomputations);
+ assertEquals(101, ncomputations);
}
}
protected static final String RELEASED = "released";
- private EventTracker<String> _tracker;
+ private EventTracker<String> tracker;
/*
* (non-Javadoc)
*/
@Override
protected void setUp() throws Exception {
- _tracker = new EventTracker<String>();
+ tracker = new EventTracker<String>();
}
protected EventTracker<String> getTracker() {
- return _tracker;
+ return tracker;
}
/**
Thread t2 = runThread();
TimingUtils.sleep(SLEEP_TIME / 10); // give threads a chance to start
// up.
- assertEquals(2, _tracker.getEventCount(STARTED)); // both threads
+ assertEquals(2, tracker.getEventCount(STARTED)); // both threads
// should have
// started.
- assertEquals(1, _tracker.getEventCount(ACQUIRED)); // one thread has
+ assertEquals(1, tracker.getEventCount(ACQUIRED)); // one thread has
// acquired the
// lock.
TimingUtils.sleep(SLEEP_TIME);
- assertEquals(2, _tracker.getEventCount(ACQUIRED)); // now the other
+ assertEquals(2, tracker.getEventCount(ACQUIRED)); // now the other
// thread could also
// acquire the lock
- assertEquals(1, _tracker.getEventCount(RELEASED)); // and the first
+ assertEquals(1, tracker.getEventCount(RELEASED)); // and the first
// thread has
// released it.
TimingUtils.sleep(SLEEP_TIME);
- assertEquals(2, _tracker.getEventCount(RELEASED)); // both threads
+ assertEquals(2, tracker.getEventCount(RELEASED)); // both threads
// should be
// finished.
t1.join();
*/
public class JvmLockTest extends AbstractLockTestCase {
- private JvmLock _lock;
+ private JvmLock lock;
/*
* (non-Javadoc)
@Override
protected void setUp() throws Exception {
super.setUp();
- _lock = new JvmLock();
+ lock = new JvmLock();
}
protected Thread runThread() {
Thread t = new Thread(new Runnable() {
public void run() {
getTracker().eventOccurred(STARTED);
- _lock.acquire();
+ lock.acquire();
getTracker().eventOccurred(ACQUIRED);
TimingUtils.sleep(SLEEP_TIME);
- _lock.release();
+ lock.release();
getTracker().eventOccurred(RELEASED);
};
});
*
*/
private static final int TWO_SECONDS = 2000;
- private ReadWriteLock _lock;
- private int _nReaders;
- private int _nWriters;
+ private ReadWriteLock lock;
+ private int nReaders;
+ private int nWriters;
/**
* Constructor for ReadWriteLockTest.
}
private synchronized int getReaderCount() {
- return _nReaders;
+ return nReaders;
}
private synchronized int getWriterCount() {
- return _nWriters;
+ return nWriters;
}
synchronized void incrementReaderCount() {
- _nReaders++;
+ nReaders++;
}
synchronized void incrementWriterCount() {
- _nWriters++;
+ nWriters++;
}
synchronized void decrementReaderCount() {
- _nReaders--;
+ nReaders--;
}
synchronized void decrementWriterCount() {
- _nWriters--;
+ nWriters--;
}
/*
*/
protected void setUp() throws Exception {
super.setUp();
- _lock = new ReadWriteLock();
+ lock = new ReadWriteLock();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
- _lock = null;
+ lock = null;
super.tearDown();
}
* Acquire and release a read lock.
*/
public void testRead() {
- _lock.acquireRead();
- _lock.releaseRead();
+ lock.acquireRead();
+ lock.releaseRead();
}
/**
* Acquire and release a write lock.
*/
public void testWrite() {
- _lock.acquireWrite();
- _lock.releaseWrite();
+ lock.acquireWrite();
+ lock.releaseWrite();
}
/**
* @throws InterruptedException May not occur.
*/
public void testMultipleReaders() throws InterruptedException {
- Runnable runnable = new ReadLocker(_lock, this, TWO_SECONDS);
+ Runnable runnable = new ReadLocker(lock, this, TWO_SECONDS);
Thread t1 = new Thread(runnable);
t1.start();
* @throws InterruptedException May not occur.
*/
public void testSingleWriter() throws InterruptedException {
- WriteLocker writer = new WriteLocker(_lock, this, ONE_SECOND);
+ WriteLocker writer = new WriteLocker(lock, this, ONE_SECOND);
Thread t1 = new Thread(writer);
Thread t2 = new Thread(writer);
* @throws InterruptedException May not occur.
*/
public void testMultipleWriters() throws InterruptedException {
- WriteLocker writer1 = new WriteLocker(_lock, this, HALF_SECOND + ONE_SECOND);
- WriteLocker writer2 = new WriteLocker(_lock, this, ONE_SECOND);
+ WriteLocker writer1 = new WriteLocker(lock, this, HALF_SECOND + ONE_SECOND);
+ WriteLocker writer2 = new WriteLocker(lock, this, ONE_SECOND);
Thread t1 = new Thread(writer1);
Thread t2 = new Thread(writer2);
* @throws InterruptedException May not occur.
*/
public void testReadWrite1() throws InterruptedException {
- ReadLocker readLocker = new ReadLocker(_lock, this, TWO_SECONDS);
+ ReadLocker readLocker = new ReadLocker(lock, this, TWO_SECONDS);
Thread t1 = new Thread(readLocker);
- WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS);
+ WriteLocker writeLocker = new WriteLocker(lock, this, TWO_SECONDS);
Thread t2 = new Thread(writeLocker);
t1.start(); // acquire read lock
* @throws InterruptedException May not occur.
*/
public void testReadWrite2() throws InterruptedException {
- ReadLocker readLocker1 = new ReadLocker(_lock, this, TWO_SECONDS + HALF_SECOND);
- ReadLocker readLocker2 = new ReadLocker(_lock, this, TWO_SECONDS + HALF_SECOND);
+ ReadLocker readLocker1 = new ReadLocker(lock, this, TWO_SECONDS + HALF_SECOND);
+ ReadLocker readLocker2 = new ReadLocker(lock, this, TWO_SECONDS + HALF_SECOND);
Thread t1 = new Thread(readLocker1);
Thread t2 = new Thread(readLocker2);
- WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS);
+ WriteLocker writeLocker = new WriteLocker(lock, this, TWO_SECONDS);
Thread t3 = new Thread(writeLocker);
t1.start(); // acquire read lock [0, 2.5]
* @throws InterruptedException May not occur.
*/
public void testReadWrite3() throws InterruptedException {
- ReadLocker readLocker = new ReadLocker(_lock, this, TWO_SECONDS);
+ ReadLocker readLocker = new ReadLocker(lock, this, TWO_SECONDS);
Thread t1 = new Thread(readLocker);
- WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS);
+ WriteLocker writeLocker = new WriteLocker(lock, this, TWO_SECONDS);
Thread t2 = new Thread(writeLocker);
t2.start(); // acquire write lock
try {
t1 = new Thread(new Runnable() {
public void run() {
- ReadWriteLockTest.this._lock.acquireRead();
+ ReadWriteLockTest.this.lock.acquireRead();
}
});
t1.start();
Thread.sleep(ONE_SECOND); // wait until thread is started
- _lock.releaseRead(); // release lock from wrong thread.
+ lock.releaseRead(); // release lock from wrong thread.
} catch (RuntimeException e) {
return; // ok
} finally {
try {
t1 = new Thread(new Runnable() {
public void run() {
- ReadWriteLockTest.this._lock.acquireWrite();
+ ReadWriteLockTest.this.lock.acquireWrite();
}
});
t1.start();
Thread.sleep(ONE_SECOND); // wait until thread is started
- _lock.releaseWrite(); // release lock from wrong thread.
+ lock.releaseWrite(); // release lock from wrong thread.
} catch (RuntimeException e) {
return; // ok
} finally {
*/
public void testAcquireReadTwice() {
try {
- _lock.acquireRead();
- _lock.acquireRead();
+ lock.acquireRead();
+ lock.acquireRead();
} catch (RuntimeException e) {
// ok
return;
*/
public void testAcquireWriteTwice() {
try {
- _lock.acquireWrite();
- _lock.acquireWrite();
+ lock.acquireWrite();
+ lock.acquireWrite();
} catch (RuntimeException e) {
return; // ok
}
*/
public void testAcquireReadFollowedByWrite() {
try {
- _lock.acquireRead();
- _lock.acquireWrite();
+ lock.acquireRead();
+ lock.acquireWrite();
} catch (RuntimeException e) {
return; // ok
}
*/
public void testAcquireWriteFollowedByRead() {
try {
- _lock.acquireWrite();
- _lock.acquireRead();
+ lock.acquireWrite();
+ lock.acquireRead();
} catch (RuntimeException e) {
return; // ok
}
*/
public void testAcquireReadFollowedByReleaseaWrite() {
try {
- _lock.acquireRead();
- _lock.releaseWrite();
+ lock.acquireRead();
+ lock.releaseWrite();
} catch (RuntimeException e) {
return; // ok
}
*/
public void testAcquireWriteFollowedByReleaseRead() {
try {
- _lock.acquireWrite();
- _lock.releaseRead();
+ lock.acquireWrite();
+ lock.releaseRead();
} catch (RuntimeException e) {
return; // ok
}
* lock, and performs a callback after the lock has been released.
*/
class ReadLocker implements Runnable {
- private ReadWriteLock _lock;
- private ReadWriteLockTest _lockTest;
- private int _sleepTime;
+ private ReadWriteLock lock;
+ private ReadWriteLockTest lockTest;
+ private int sleepTime;
public ReadLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest,
int aSleepTime) {
- _lock = aLock;
- _lockTest = aLockTest;
- _sleepTime = aSleepTime;
+ lock = aLock;
+ lockTest = aLockTest;
+ sleepTime = aSleepTime;
}
public void run() {
- _lock.acquireRead();
- _lockTest.incrementReaderCount();
+ lock.acquireRead();
+ lockTest.incrementReaderCount();
try {
- Thread.sleep(_sleepTime);
+ Thread.sleep(sleepTime);
} catch (InterruptedException e) {
Assert.fail("ReadLocker thread was interrupted."
+ Thread.currentThread());
}
- _lock.releaseRead();
- _lockTest.decrementReaderCount();
+ lock.releaseRead();
+ lockTest.decrementReaderCount();
}
}
* lock, and performs a callback after the lock has been released.
*/
class WriteLocker implements Runnable {
- private ReadWriteLock _lock;
- private ReadWriteLockTest _lockTest;
- private int _sleepTime;
+ private ReadWriteLock lock;
+ private ReadWriteLockTest lockTest;
+ private int sleepTime;
public WriteLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest,
int aSleepTime) {
- _lock = aLock;
- _lockTest = aLockTest;
- _sleepTime = aSleepTime;
+ lock = aLock;
+ lockTest = aLockTest;
+ sleepTime = aSleepTime;
}
public void run() {
- _lock.acquireWrite();
- _lockTest.incrementWriterCount();
+ lock.acquireWrite();
+ lockTest.incrementWriterCount();
try {
- Thread.sleep(_sleepTime);
+ Thread.sleep(sleepTime);
} catch (InterruptedException e) {
Assert.fail("WriteLocker thread was interrupted: "
+ Thread.currentThread());
}
- _lock.releaseWrite();
- _lockTest.decrementWriterCount();
+ lock.releaseWrite();
+ lockTest.decrementWriterCount();
}
}
*/
public class GreaterThanCondition implements Condition<Integer> {
- private int _value;
+ private int value;
public GreaterThanCondition(int aValue) {
- _value = aValue;
+ value = aValue;
}
/* (non-Javadoc)
* @see org.wamblee.conditions.Condition#matches(T)
*/
public boolean matches(Integer aObject) {
- return aObject > _value;
+ return aObject > value;
}
}
*/
public class LessThanCondition implements Condition<Integer> {
- private int _value;
+ private int value;
public LessThanCondition(int aValue) {
- _value = aValue;
+ value = aValue;
}
/* (non-Javadoc)
* @see org.wamblee.conditions.Condition#matches(T)
*/
public boolean matches(Integer aObject) {
- return aObject < _value;
+ return aObject < value;
}
}
*/
public class TestBean {
- private String _value;
+ private String value;
public TestBean(String aValue) {
- _value = aValue;
+ value = aValue;
}
public String getValue() {
- return _value;
+ return value;
}
private String getPrivateValue() {
- return _value;
+ return value;
}
}
private static final String REGEX = "^.*\\.txt$";
private static final String FILE1 = "file1.txt";
- private TestData _data;
- private DirectoryMonitor.Listener _listener;
+ private TestData data;
+ private DirectoryMonitor.Listener listener;
- private DirectoryMonitor _monitor;
+ private DirectoryMonitor monitor;
@Override
protected void setUp() throws Exception {
super.setUp();
- _data = new TestData(this);
- _data.clean();
- _listener = mock(DirectoryMonitor.Listener.class);
- _monitor = new DirectoryMonitor(_data.getRoot(), new AwkFilenameFilter(
- REGEX), _listener);
+ data = new TestData(this);
+ data.clean();
+ listener = mock(DirectoryMonitor.Listener.class);
+ monitor = new DirectoryMonitor(data.getRoot(), new AwkFilenameFilter(
+ REGEX), listener);
}
public void testEmptyDir() {
// Nothing is expected to be called.
for (int i = 0; i < 10; i++) {
- _monitor.poll();
- verifyNoMoreInteractions(_listener);
+ monitor.poll();
+ verifyNoMoreInteractions(listener);
}
}
public void testFileCreated() {
- _data.createFile(FILE1, "hello");
- _monitor.poll();
- verify(_listener).fileCreated(_data.getFile(FILE1));
+ data.createFile(FILE1, "hello");
+ monitor.poll();
+ verify(listener).fileCreated(data.getFile(FILE1));
}
public void testFileDeleted() {
- _data.createFile(FILE1, "hello");
- _monitor.poll();
- reset(_listener);
+ data.createFile(FILE1, "hello");
+ monitor.poll();
+ reset(listener);
- _data.deleteFile(FILE1);
- _monitor.poll();
+ data.deleteFile(FILE1);
+ monitor.poll();
- verify(_listener).fileDeleted(_data.getFile(FILE1));
- verifyNoMoreInteractions(_listener);
+ verify(listener).fileDeleted(data.getFile(FILE1));
+ verifyNoMoreInteractions(listener);
}
public void testFileChanged() throws InterruptedException {
- _data.createFile(FILE1, "hello");
- _monitor.poll();
- reset(_listener);
+ data.createFile(FILE1, "hello");
+ monitor.poll();
+ reset(listener);
Thread.sleep(2000);
- _data.deleteFile(FILE1);
- _data.createFile(FILE1, "bla");
+ data.deleteFile(FILE1);
+ data.createFile(FILE1, "bla");
- _monitor.poll();
- verify(_listener).fileChanged(_data.getFile(FILE1));
- verifyNoMoreInteractions(_listener);
+ monitor.poll();
+ verify(listener).fileChanged(data.getFile(FILE1));
+ verifyNoMoreInteractions(listener);
}
public void testFileFilterIsUsed() {
- _monitor.poll();
+ monitor.poll();
- _data.createFile("file.xml", "hello");
- _monitor.poll();
- verifyNoMoreInteractions(_listener);
+ data.createFile("file.xml", "hello");
+ monitor.poll();
+ verifyNoMoreInteractions(listener);
}
public void testDirectoryIsIgnored() {
- _monitor.poll();
- _data.createDir(FILE1);
- _monitor.poll();
- verifyNoMoreInteractions(_listener);
+ monitor.poll();
+ data.createDir(FILE1);
+ monitor.poll();
+ verifyNoMoreInteractions(listener);
}
public void testExceptionsWIllLeadToRepeatedNotifications() {
- _monitor.poll();
- _data.createFile(FILE1, "hello");
+ monitor.poll();
+ data.createFile(FILE1, "hello");
- stubVoid(_listener).toThrow(new RuntimeException()).on().
- fileCreated(_data.getFile(FILE1));
+ stubVoid(listener).toThrow(new RuntimeException()).on().
+ fileCreated(data.getFile(FILE1));
try {
- _monitor.poll();
+ monitor.poll();
} catch (RuntimeException e) {
- reset(_listener);
+ reset(listener);
// polling again should lead to the same filecreated call.
// this time no exception is thrown.
- _monitor.poll();
- verify(_listener).fileCreated(_data.getFile(FILE1));
- verifyNoMoreInteractions(_listener);
+ monitor.poll();
+ verify(listener).fileCreated(data.getFile(FILE1));
+ verifyNoMoreInteractions(listener);
return;
}
fail(); // should not get here.
*/
public final class TestData {
- private Object _testcase;
- private File _root;
+ private Object testcase;
+ private File root;
/**
* Test data to be constructed in the setUp of a test. {@link #clean()} must
* test.
*/
public TestData(Object aTestcase) {
- _testcase = aTestcase;
- _root = getTestRootDir(aTestcase);
- FileSystemUtils.createDir(_root);
+ testcase = aTestcase;
+ root = getTestRootDir(aTestcase);
+ FileSystemUtils.createDir(root);
}
/**
public void createFile(String aRelative, String aFile, InputStream aContents) {
FileSystemUtils
- .createFile(new File(_root, aRelative), aFile, aContents);
+ .createFile(new File(root, aRelative), aFile, aContents);
}
public void createFile(String aFile, String aContents) {
public void createFile(String aRelative, String aFile, String aContents) {
InputStream is = new ByteArrayInputStream(aContents.getBytes());
- FileSystemUtils.createFile(new File(_root, aRelative), aFile, is);
+ FileSystemUtils.createFile(new File(root, aRelative), aFile, is);
}
public void deleteFile(String aFile) {
}
public void deleteFile(String aRelative, String aFile) {
- FileSystemUtils.delete(new File(_root, aFile));
+ FileSystemUtils.delete(new File(root, aFile));
}
/**
* @return Temporary directory.
*/
public File getTmpDir() {
- return new File(_root, "tmpdir");
+ return new File(root, "tmpdir");
}
/**
* Cleans up the test output directory.
*/
public void clean() {
- FileSystemUtils.deleteDirRecursively(_root);
- FileSystemUtils.createDir(_root);
+ FileSystemUtils.deleteDirRecursively(root);
+ FileSystemUtils.createDir(root);
}
/**
* Source directory to copy.
*/
public void copyDir(File aSrc) {
- FileSystemUtils.copyDir(aSrc, _root);
+ FileSystemUtils.copyDir(aSrc, root);
}
/**
public void copyResource(String aResource, String aRelativePath) {
try {
InputStream is = new ClassPathResource(aResource).getInputStream();
- FileOutputStream fos = new FileOutputStream(new File(_root,
+ FileOutputStream fos = new FileOutputStream(new File(root,
aRelativePath));
FileSystemUtils.copyStream(is, fos);
} catch (IOException e) {
}
public void createDir(String aRelative) {
- FileSystemUtils.createDir(new File(_root, aRelative));
+ FileSystemUtils.createDir(new File(root, aRelative));
}
/**
* cannot be removed.
*/
public void delete(String aRelative) {
- FileSystemUtils.delete(new File(_root, aRelative));
+ FileSystemUtils.delete(new File(root, aRelative));
}
/**
* Relative path.
*/
public void deleteDir(String aRelative) {
- FileSystemUtils.deleteDir(new File(_root, aRelative));
+ FileSystemUtils.deleteDir(new File(root, aRelative));
}
/**
* Relative path.
*/
public void deleteDirRecursively(String aRelative) {
- FileSystemUtils.deleteDir(new File(_root, aRelative));
+ FileSystemUtils.deleteDir(new File(root, aRelative));
}
/**
* @return Root of the test output.
*/
public File getRoot() {
- return _root;
+ return root;
}
/**
* Gets a file object for a relative path.
*/
public File getFile(String aRelative) {
- return new File(_root, aRelative);
+ return new File(root, aRelative);
}
}
private static final String UPDATE = "send";
- private Integer _observed;
- private Observable<Integer, String> _observable;
+ private Integer observed;
+ private Observable<Integer, String> observable;
/*
* (non-Javadoc)
@Override
protected void setUp() throws Exception {
super.setUp();
- _observed = new Integer(1);
- _observable = new Observable<Integer, String>(_observed,
+ observed = new Integer(1);
+ observable = new Observable<Integer, String>(observed,
new DefaultObserverNotifier());
}
final Observer mockObserver = mock(Observer.class);
InOrder order = inOrder(mockObserver);
- long subscription = _observable.subscribe(mockObserver);
+ long subscription = observable.subscribe(mockObserver);
- assertEquals(1, _observable.getObserverCount());
+ assertEquals(1, observable.getObserverCount());
final String message = "hallo";
- _observable.send(message);
+ observable.send(message);
- order.verify(mockObserver).send(_observed, message);
+ order.verify(mockObserver).send(observed, message);
verifyNoMoreInteractions(mockObserver);
- _observable.unsubscribe(subscription);
- assertEquals(0, _observable.getObserverCount());
+ observable.unsubscribe(subscription);
+ assertEquals(0, observable.getObserverCount());
- _observable.send(message);
+ observable.send(message);
verifyNoMoreInteractions(mockObserver);
}
for (int i = 0; i < nsubscribers; i++) {
mocks[i] = mock(Observer.class);
order[i] = inOrder(mocks[i]);
- long subscription = _observable.subscribe(mocks[i]);
+ long subscription = observable.subscribe(mocks[i]);
assertTrue(subscriptions.add(subscription));
}
- assertEquals(nsubscribers, _observable.getObserverCount());
+ assertEquals(nsubscribers, observable.getObserverCount());
final String message = "hallo";
- _observable.send(message);
+ observable.send(message);
for (int i = 0; i < nsubscribers; i++) {
- order[i].verify(mocks[i]).send(_observed, message);
+ order[i].verify(mocks[i]).send(observed, message);
}
for (int i = nsubscribers / 2; i < nsubscribers; i++) {
- _observable.unsubscribe(subscriptions.get(i));
+ observable.unsubscribe(subscriptions.get(i));
}
assertEquals(nsubscribers - (nsubscribers - nsubscribers / 2),
- _observable.getObserverCount());
+ observable.getObserverCount());
final String message2 = "blabla";
- _observable.send(message2);
+ observable.send(message2);
for (int i = 0; i < nsubscribers / 2; i++) {
- order[i].verify(mocks[i]).send(_observed, message2);
+ order[i].verify(mocks[i]).send(observed, message2);
}
for (int i = nsubscribers/2; i < nsubscribers; i++) {
verifyNoMoreInteractions(mocks[i]);
public void testUnsubscribeWithWrongSubscription() {
Observer<Integer, String> observer = mock(Observer.class);
- long subscription = _observable.subscribe(observer);
+ long subscription = observable.subscribe(observer);
- assertEquals(1, _observable.getObserverCount());
+ assertEquals(1, observable.getObserverCount());
try {
- _observable.unsubscribe(subscription + 1);
+ observable.unsubscribe(subscription + 1);
} catch (IllegalArgumentException e) {
return; // ok
}
/**
* Map of Thread object to a list of events.
*/
- private Map<Thread, List<Event>> _events;
+ private Map<Thread, List<Event>> events;
/**
* Constructs the event tracker.
}
public void clear() {
- _events = new HashMap<Thread, List<Event>>();
+ events = new HashMap<Thread, List<Event>>();
}
/**
public synchronized void eventOccurred(Event aEvent) {
LOG.info("Event '" + aEvent + "' sent.");
Thread current = Thread.currentThread();
- List<Event> events = _events.get(current);
- if (events == null) {
- events = new ArrayList<Event>();
- _events.put(current, events);
+ List<Event> eventList = events.get(current);
+ if (eventList == null) {
+ eventList = new ArrayList<Event>();
+ events.put(current, eventList);
}
- events.add(aEvent);
+ eventList.add(aEvent);
}
/**
* @return Whether or not the event was sent.
*/
public synchronized boolean isEventSent(Thread aThread, Event aEvent) {
- List<Event> events = _events.get(aThread);
- if (events == null) {
+ List<Event> eventList = events.get(aThread);
+ if (eventList == null) {
return false;
}
- return events.contains(aEvent);
+ return eventList.contains(aEvent);
}
/**
* events were sent.
*/
public synchronized List<Event> getEvents(Thread aThread) {
- List<Event> events = _events.get(aThread);
- if (events == null) {
- events = Collections.emptyList();
+ List<Event> eventList = events.get(aThread);
+ if (eventList == null) {
+ eventList = Collections.emptyList();
}
- return Collections.unmodifiableList(events);
+ return Collections.unmodifiableList(eventList);
}
/**
*/
public synchronized int getEventCount(Event aEvent) {
int count = 0;
- for (Thread thread : _events.keySet()) {
- List<Event> events = _events.get(thread);
- for (Event event : events) {
+ for (Thread thread : events.keySet()) {
+ List<Event> eventList = events.get(thread);
+ for (Event event : eventList) {
if (event.equals(aEvent)) {
count++;
}
*/
public synchronized int getEventCount() {
int count = 0;
- for (Thread thread: _events.keySet()) {
- count += _events.get(thread).size();
+ for (Thread thread: events.keySet()) {
+ count += events.get(thread).size();
}
return count;
}
*/
public class ClasspathUriResolverTest extends TestCase {
- private URIResolver _resolver;
+ private URIResolver resolver;
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
- _resolver = new ClasspathUriResolver();
+ resolver = new ClasspathUriResolver();
}
/**
* @throws IOException
*/
public void testResolveExistingFile() throws TransformerException, IOException {
- Source source = _resolver.resolve("org/wamblee/xml/reportToHtml.xsl", "");
+ Source source = resolver.resolve("org/wamblee/xml/reportToHtml.xsl", "");
assertTrue(source instanceof StreamSource);
String resolved = FileSystemUtils.read(((StreamSource)source).getInputStream());
*/
public void testResolveNonExistingFile() {
try {
- Source source = _resolver.resolve("org/wamblee/xml/reportToHtml-nonexisting.xsl", "");
+ Source source = resolver.resolve("org/wamblee/xml/reportToHtml-nonexisting.xsl", "");
} catch (TransformerException e) {
return; // ok
}
/**
* Lock to use.
*/
- private Lock _lock;
+ private Lock lock;
/**
* Constructs lock advice.
* @param aLock Lock to use.
*/
public LockAdvice(Lock aLock) {
- _lock = aLock;
+ lock = aLock;
}
/* (non-Javadoc)
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
public Object invoke(MethodInvocation aInvocation) throws Throwable {
- _lock.acquire();
+ lock.acquire();
try {
return aInvocation.proceed();
} finally {
- _lock.release();
+ lock.release();
}
}
*/
public class SpringBeanFactory implements BeanFactory {
- private BeanFactoryReference _factoryReference;
+ private BeanFactoryReference factoryReference;
/**
* Constructs the bean factory.
try {
BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator
.getInstance(aSelector);
- _factoryReference = locator.useBeanFactory(aFactoryName);
+ factoryReference = locator.useBeanFactory(aFactoryName);
} catch (BeansException e) {
throw new BeanFactoryException(
"Could not load bean factory: selector = '" + aSelector
*/
public <T> T find(String aId, Class<T> aClass) {
try {
- Object obj = _factoryReference.getFactory().getBean(aId, aClass);
+ Object obj = factoryReference.getFactory().getBean(aId, aClass);
assert obj != null;
return aClass.cast(obj);
} catch (BeansException e) {
* @return Spring bean factory.
*/
public org.springframework.beans.factory.BeanFactory getSpringBeanFactory() {
- return _factoryReference.getFactory();
+ return factoryReference.getFactory();
}
}
*
*/
private static final class ObjectElem {
- private Object _object;
+ private Object object;
public ObjectElem(Object aObject) {
- _object = aObject;
+ object = aObject;
}
public boolean equals(Object aObj) {
- return ((ObjectElem) aObj)._object == _object;
+ return ((ObjectElem) aObj).object == object;
}
public int hashCode() {
- return _object.hashCode();
+ return object.hashCode();
}
}
}
}
- private Runnable _target;
+ private Runnable target;
/*
* (non-Javadoc)
support.setInterfaces(new Class[]{ Runnable.class });
support.setTarget(runner);
support.addAdvice(advice);
- _target = (Runnable)support.getObject();
+ target = (Runnable)support.getObject();
}
public void run() {
try {
getTracker().eventOccurred(STARTED);
- _target.run();
+ target.run();
getTracker().eventOccurred(RELEASED);
} catch (Throwable e) {
throw new RuntimeException(e);
*/
public class TestSpringBeanFactory implements BeanFactory {
- private ApplicationContext _context;
+ private ApplicationContext context;
public TestSpringBeanFactory(ApplicationContext aContext) {
- _context = aContext;
+ context = aContext;
}
/* (non-Javadoc)
*/
public <T> T find(String aId, Class<T> aClass) {
try {
- Object obj = _context.getBean(aId, aClass);
+ Object obj = context.getBean(aId, aClass);
assert obj != null;
return aClass.cast(obj);
} catch (BeansException e) {
public class ClassConfiguration {
private Class _class;
- private ConstructorConfiguration _constructorConfig;
- private ObjectConfiguration _objectConfig;
+ private ConstructorConfiguration constructorConfig;
+ private ObjectConfiguration objectConfig;
/**
* Constructs the configuration. By default no constructor is selected and
*/
public ClassConfiguration(Class aClass) {
_class = aClass;
- _constructorConfig = new ConstructorConfiguration(aClass);
- _objectConfig = new ObjectConfiguration(aClass);
+ constructorConfig = new ConstructorConfiguration(aClass);
+ objectConfig = new ObjectConfiguration(aClass);
}
public ConstructorConfiguration getConstructorConfig() {
- return _constructorConfig;
+ return constructorConfig;
}
public ObjectConfiguration getObjectConfig() {
- return _objectConfig;
+ return objectConfig;
}
/**
* @return object.
*/
public Object create(Scope aScope) {
- return _constructorConfig.create(aScope);
+ return constructorConfig.create(aScope);
}
/**
* @param aScope Scope in which injection takes place.
*/
public void inject(Scope aScope, Object aObject) {
- _objectConfig.inject(aScope, aObject);
+ objectConfig.inject(aScope, aObject);
}
public List<ProvidedInterface> getProvidedInterfaces() {
public List<RequiredInterface> getRequiredInterfaces() {
List<RequiredInterface> result = new ArrayList<RequiredInterface>();
- result.addAll(_constructorConfig.getRequiredInterfaces());
- result.addAll(_objectConfig.getRequiredInterfaces());
+ result.addAll(constructorConfig.getRequiredInterfaces());
+ result.addAll(objectConfig.getRequiredInterfaces());
return result;
}
}
* </ul>
*/
public class ConstructorConfiguration {
- private Class _class;
- private Constructor<?> _constructor;
- private ParameterValues _values;
- private boolean _publicOnly;
+ private Class clazz;
+ private Constructor<?> constructor;
+ private ParameterValues values;
+ private boolean publicOnly;
/**
* Constructs the configuration. By default the public constructor with the
* @param aClass Class to construct.
*/
public ConstructorConfiguration(Class aClass) {
- _class = aClass;
- _constructor = null;
- _publicOnly = true;
+ clazz = aClass;
+ constructor = null;
+ publicOnly = true;
}
/**
* @return
*/
public ConstructorConfiguration setNonPublic(boolean aNonPublic) {
- _publicOnly = !aNonPublic;
- _constructor = null;
- _values = null;
+ publicOnly = !aNonPublic;
+ constructor = null;
+ values = null;
return this;
}
*/
public ConstructorConfiguration select(Class... aTypes) {
try {
- _constructor = _class.getDeclaredConstructor(aTypes);
+ constructor = clazz.getDeclaredConstructor(aTypes);
} catch (Exception e) {
throw new SystemAssemblyException(e.getMessage(), e);
}
* identified.
*/
public ConstructorConfiguration greedy() {
- Constructor<?>[] declared = _class.getDeclaredConstructors();
+ Constructor<?>[] declared = clazz.getDeclaredConstructors();
if (declared.length == 0) {
- throw new SystemAssemblyException("Class '" + _class
+ throw new SystemAssemblyException("Class '" + clazz
+ " is an interface, primitive type, or array");
}
int max = -1;
new Condition<Constructor<?>>() {
@Override
public boolean matches(Constructor<?> aObject) {
- if ( !_publicOnly ) {
+ if ( !publicOnly ) {
return true;
} else {
return Modifier.isPublic(aObject.getModifiers());
throw new SystemAssemblyException(
"Greediest constructor cannot be uniquely determined");
}
- _constructor = longest.get(0);
+ constructor = longest.get(0);
resetValues();
return this;
}
public ParameterValues getParameters() {
getConstructor(); // initialize constructor if needed.
- return _values;
+ return values;
}
/**
* Resets the values.
*/
private void resetValues() {
- _constructor.setAccessible(true);
- _values = new ParameterValues(_constructor.getParameterTypes());
+ constructor.setAccessible(true);
+ values = new ParameterValues(constructor.getParameterTypes());
}
/**
* @return object.
*/
public Object create(Scope aScope) {
- Object[] values = _values.values(aScope);
+ Object[] valueArray = values.values(aScope);
try {
- return getConstructor().newInstance(values);
+ return getConstructor().newInstance(valueArray);
} catch (Exception e) {
throw new SystemAssemblyException("Could not construct object "
- + getConstructor() + " " + Arrays.asList(values), e);
+ + getConstructor() + " " + Arrays.asList(valueArray), e);
}
}
public List<RequiredInterface> getRequiredInterfaces() {
getConstructor(); // initialize constructor if needed.
- return _values.getRequiredInterfaces();
+ return values.getRequiredInterfaces();
}
private Constructor getConstructor() {
- if (_constructor == null ) {
+ if (constructor == null ) {
greedy();
}
- return _constructor;
+ return constructor;
}
}
*/
public class ObjectAdapter extends AbstractComponent<Object> {
- private ObjectConfiguration _objectConfig;
- private Object _object;
+ private ObjectConfiguration objectConfig;
+ private Object object;
public ObjectAdapter(String aName, Object aObject, ObjectConfiguration aObjectConfig) {
super(aName,
new ProvidedInterface[] { new DefaultProvidedInterface(aName, aObject.getClass()) },
aObjectConfig.getRequiredInterfaces().toArray(new RequiredInterface[0]));
- _objectConfig = aObjectConfig;
- _object = aObject;
+ objectConfig = aObjectConfig;
+ object = aObject;
}
@Override
protected Object doStart(Scope aScope) {
- _objectConfig.inject(aScope, _object);
+ objectConfig.inject(aScope, object);
for (ProvidedInterface provided: getProvidedInterfaces()) {
- addInterface(provided, _object, aScope);
+ addInterface(provided, object, aScope);
}
- return _object;
+ return object;
}
@Override
public class ObjectConfiguration {
private Class _class;
- private SetterConfiguration _setterConfig;
+ private SetterConfiguration setterConfig;
public ObjectConfiguration(Class aClass) {
_class = aClass;
- _setterConfig = new SetterConfiguration(aClass);
+ setterConfig = new SetterConfiguration(aClass);
}
/**
* @param aObject Object.
*/
public void inject(Scope aScope, Object aObject) {
- _setterConfig.inject(aScope, aObject);
+ setterConfig.inject(aScope, aObject);
}
public SetterConfiguration getSetterConfig() {
- return _setterConfig;
+ return setterConfig;
}
public List<RequiredInterface> getRequiredInterfaces() {
List<RequiredInterface> result = new ArrayList<RequiredInterface>();
- result.addAll(_setterConfig.getRequiredInterfaces());
+ result.addAll(setterConfig.getRequiredInterfaces());
return result;
}
* @author Erik Brakkee
*/
public class ParameterValues {
- private String[] _names;
- private Class[] _types;
- private ValueProvider[] _values;
+ private String[] names;
+ private Class[] types;
+ private ValueProvider[] values;
/**
* Constructs the configuration. By default no constructor is selected and
* @param aClass Class to construct.
*/
public ParameterValues(Class[] aTypes) {
- _names = new String[aTypes.length];
+ names = new String[aTypes.length];
for (int i = 0; i < aTypes.length; i++) {
- _names[i] = "arg" + i;
+ names[i] = "arg" + i;
}
- _types = aTypes;
+ types = aTypes;
resetValues();
}
*/
public ParameterValues(String[] aNames, Class[] aTypes) {
assert aNames.length == aTypes.length;
- _names = aNames;
- _types = aTypes;
+ names = aNames;
+ types = aTypes;
resetValues();
}
* @return Types.
*/
public Class[] getTypes() {
- return _types;
+ return types;
}
/**
* @param aArg Argument to set.
*/
public ParameterValues setOptional(int aArg) {
- _values[aArg] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
- "arg" + aArg, _types[aArg], true));
+ values[aArg] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
+ "arg" + aArg, types[aArg], true));
return this;
}
* @param aValue Value.
*/
public ParameterValues setValue(int aArg, Object aValue) {
- _values[aArg] = new FixedValueProvider(aValue);
+ values[aArg] = new FixedValueProvider(aValue);
return this;
}
* Resets the values.
*/
private void resetValues() {
- _values = new ValueProvider[_types.length];
- for (int i = 0; i < _values.length; i++) {
- _values[i] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
- _names[i], _types[i]));
+ values = new ValueProvider[types.length];
+ for (int i = 0; i < values.length; i++) {
+ values[i] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
+ names[i], types[i]));
}
}
*/
public List<RequiredInterface> getRequiredInterfaces() {
List<RequiredInterface> result = new ArrayList<RequiredInterface>();
- for (ValueProvider provider: _values) {
+ for (ValueProvider provider: values) {
if ( provider instanceof RequiredInterfaceProvider) {
result.add( ((RequiredInterfaceProvider)provider).getRequiredInterface());
}
* @return Values.
*/
public Object[] values(Scope aScope) {
- Object[] values = new Object[_values.length];
- for (int i = 0; i < _values.length; i++) {
- values[i] = _values[i].getValue(aScope);
+ Object[] valueArray = new Object[values.length];
+ for (int i = 0; i < values.length; i++) {
+ valueArray[i] = values[i].getValue(aScope);
}
- return values;
+ return valueArray;
}
}
*/
class RequiredInterfaceProvider implements ValueProvider {
- private RequiredInterface _required;
+ private RequiredInterface required;
/**
* Constructs the provider
* @param aRequired Required interface.
*/
public RequiredInterfaceProvider(RequiredInterface aRequired) {
- _required = aRequired;
+ required = aRequired;
}
@Override
public Object getValue(Scope aScope) {
- return aScope.getInterfaceImplementation(_required.getProvider(), Object.class);
+ return aScope.getInterfaceImplementation(required.getProvider(), Object.class);
}
public RequiredInterface getRequiredInterface() {
- return _required;
+ return required;
}
}
public class SetterConfiguration {
private Class _class;
- private boolean _publicOnly;
+ private boolean publicOnly;
- private Map<Method, ParameterValues> _setters;
+ private Map<Method, ParameterValues> setters;
/**
* Constructs the setter configuration. By default no setters are added.
*/
public SetterConfiguration(Class aClass) {
_class = aClass;
- _publicOnly = true;
- _setters = new HashMap<Method, ParameterValues>();
+ publicOnly = true;
+ setters = new HashMap<Method, ParameterValues>();
}
/**
* Makes sure that all available setters are used.
*/
public SetterConfiguration initAllSetters() {
- _setters.clear();
- for (Method method: getAllSetters(_class, _publicOnly) ) {
- _setters.put(method, createParameterValues(method));
+ setters.clear();
+ for (Method method: getAllSetters(_class, publicOnly) ) {
+ setters.put(method, createParameterValues(method));
}
return this;
}
* Non public flag.
*/
public SetterConfiguration setNonPublic(boolean aIsNonPublic) {
- _publicOnly = !aIsNonPublic;
+ publicOnly = !aIsNonPublic;
return this;
}
* @return Reference to the current object to allow call chaining.
*/
public SetterConfiguration clear() {
- _setters.clear();
+ setters.clear();
return this;
}
* @return Reference to the current object to allow call chaining.
*/
public SetterConfiguration remove(String aName) {
- for (Method method : _setters.keySet()) {
+ for (Method method : setters.keySet()) {
if (method.getName().equals(aName)) {
- _setters.remove(method);
+ setters.remove(method);
return this;
}
}
if ( !aMethod.getDeclaringClass().isAssignableFrom(_class) ) {
throw new RuntimeException("Method " + aMethod + " not found in class " + _class + " or its superclasses");
}
- for (Method method : _setters.keySet()) {
+ for (Method method : setters.keySet()) {
if (method.equals(aMethod)) {
- _setters.remove(method);
+ setters.remove(method);
return this;
}
}
* @return Reference to the current object to allow call chaining.
*/
public SetterConfiguration add(final String aName) {
- int oldlen = _setters.size();
+ int oldlen = setters.size();
List<Method> methods = new ArrayList<Method>();
- CollectionFilter.filter(getAllSetters(_class, _publicOnly), methods,
+ CollectionFilter.filter(getAllSetters(_class, publicOnly), methods,
new Condition<Method>() {
@Override
public boolean matches(Method aObject) {
}
// TODO is it possible to get more than one setter here in case the subclass overrides
// the baseclass method?
- _setters.put(methods.get(0), createParameterValues(methods.get(0)));
+ setters.put(methods.get(0), createParameterValues(methods.get(0)));
return this;
}
*/
public SetterConfiguration addSetter(final Class aType) {
List<Method> result = new ArrayList<Method>();
- CollectionFilter.filter(getAllSetters(_class, _publicOnly), result,
+ CollectionFilter.filter(getAllSetters(_class, publicOnly), result,
new Condition<Method>() {
@Override
public boolean matches(Method aObject) {
+ setters);
}
Method method = result.get(0);
- _setters.put(method, createParameterValues(method));
+ setters.put(method, createParameterValues(method));
return this;
}
*/
public List<RequiredInterface> getRequiredInterfaces() {
List<RequiredInterface> result = new ArrayList<RequiredInterface>();
- for (Method method : _setters.keySet()) {
- result.addAll(_setters.get(method).getRequiredInterfaces());
+ for (Method method : setters.keySet()) {
+ result.addAll(setters.get(method).getRequiredInterfaces());
}
return result;
}
throw new IllegalArgumentException("Object '" + aObject
+ "' is not an instance of " + _class.getName());
}
- for (Method method : _setters.keySet()) {
- ParameterValues values = _setters.get(method);
+ for (Method method : setters.keySet()) {
+ ParameterValues values = setters.get(method);
try {
method.invoke(aObject, values.values(aScope));
* @return Parameter values.
*/
public ParameterValues values(String aMethod) {
- for (Method method : _setters.keySet()) {
+ for (Method method : setters.keySet()) {
if (method.getName().equals(aMethod)) {
- return _setters.get(method);
+ return setters.get(method);
}
}
throw new IllegalArgumentException("No setter method '" + aMethod
}
public List<Method> getSetters() {
- return new ArrayList<Method>(_setters.keySet());
+ return new ArrayList<Method>(setters.keySet());
}
}
}
};
- private boolean _schemaUpdate;
- private DatabaseType _type;
+ private boolean schemaUpdate;
+ private DatabaseType type;
public ORMappingConfig(boolean aSchemaUpdate, DatabaseType aType) {
- _schemaUpdate = aSchemaUpdate;
- _type = aType;
+ schemaUpdate = aSchemaUpdate;
+ type = aType;
}
public boolean isSchemaUpdate() {
- return _schemaUpdate;
+ return schemaUpdate;
}
public DatabaseType getType() {
- return _type;
+ return type;
}
}
private static ProvidedInterface PROPS = new DefaultProvidedInterface("props", Properties.class);
- private Properties _props;
+ private Properties props;
public PropertyComponent(String aName, InputResource aResource) throws IOException {
this(aName, readProps(aResource));
public PropertyComponent(String aName, Properties aProps) {
super(aName);
- _props = aProps;
+ props = aProps;
addProvidedInterface(PROPS);
}
@Override
protected Properties doStart(Scope aScope) {
- addInterface(PROPS, _props, aScope);
- return _props;
+ addInterface(PROPS, props, aScope);
+ return props;
}
@Override
private static final Log LOG = LogFactory.getLog(Container.class);
- private List<Component> _components;
- private CompositeEdgeFilter _edgeFilter;
- private boolean _sealed;
+ private List<Component> components;
+ private CompositeEdgeFilter edgeFilter;
+ private boolean sealed;
/**
* Constructs the container
public Container(String aName, Component[] aComponents,
List<ProvidedInterface> aProvided, List<RequiredInterface> aRequired) {
super(aName, aProvided, aRequired);
- _components = new ArrayList<Component>();
+ components = new ArrayList<Component>();
- _edgeFilter = new CompositeEdgeFilter();
- _sealed = false;
+ edgeFilter = new CompositeEdgeFilter();
+ sealed = false;
for (Component component : aComponents) {
addComponent(component);
}
throw new SystemAssemblyException("Duplicate component '"
+ aComponent.getName() + "'");
}
- _components.add(aComponent);
+ components.add(aComponent);
aComponent.addContext(getQualifiedName());
return this;
}
+ aProvidedInterface + "'");
}
}
- _edgeFilter.add(new ConnectRequiredProvidedEdgeFilter(aClientComponent, aRequiredInterface, aServerComponent, aProvidedInterface));
+ edgeFilter.add(new ConnectRequiredProvidedEdgeFilter(aClientComponent, aRequiredInterface, aServerComponent, aProvidedInterface));
}
/**
+ aExternalRequiredInterface + "'");
}
}
- _edgeFilter.add(new ConnectRequiredExternallyRequiredEdgeFilter(
+ edgeFilter.add(new ConnectRequiredExternallyRequiredEdgeFilter(
aComponent, aRequiredInterface, aExternalRequiredInterface));
}
+ aExternalProvided + "'");
}
}
- _edgeFilter.add(new ConnectExternalProvidedProvidedFilter(aExternalProvided, aComponent, aProvidedInterface));
+ edgeFilter.add(new ConnectExternalProvidedProvidedFilter(aExternalProvided, aComponent, aProvidedInterface));
}
@Override
public void addContext(String aContext) {
super.addContext(aContext);
- for (Component component : _components) {
+ for (Component component : components) {
component.addContext(aContext);
}
}
* be added.
*/
public void seal() {
- _sealed = true;
+ sealed = true;
}
/**
* @return True iff the container is sealed.
*/
public boolean isSealed() {
- return _sealed;
+ return sealed;
}
/**
LOG.info("Starting '" + getQualifiedName() + "'");
List<Component> started = new ArrayList<Component>();
- for (Component component : _components) {
+ for (Component component : components) {
try {
// Start the service.
if (!aDryRun) {
for (RequiredInterface req : getRequiredInterfaces()) {
graph.addRequiredInterface(this, req);
}
- for (Component comp : _components) {
+ for (Component comp : components) {
graph.addComponent(comp);
}
for (ProvidedInterface prov: getProvidedInterfaces()) {
graph.addProvidedInterface(this, prov);
}
- graph.addEdgeFilter(_edgeFilter);
+ graph.addEdgeFilter(edgeFilter);
return graph;
}
@Override
protected void doStop(Scope aScope) {
- for (int i = _components.size() - 1; i >= 0; i--) {
- Component component = _components.get(i);
+ for (int i = components.size() - 1; i >= 0; i--) {
+ Component component = components.get(i);
Object runtime = aScope.getRuntime(component);
component.stop(runtime);
}
}
private void checkSealed() {
- if (_sealed) {
+ if (sealed) {
throw new SystemAssemblyException("Container is sealed");
}
}
* @return Component or null if not found.
*/
public Component findComponent(String aName) {
- for (Component<?> component: _components) {
+ for (Component<?> component: components) {
if ( component.getName().equals(aName)) {
return component;
}
private static final Log LOG = LogFactory.getLog(AbstractComponent.class);
- private ThreadLocal<List<ProvidedInterface>> _remaining;
+ private ThreadLocal<List<ProvidedInterface>> remaining;
- private String _context;
- private String _name;
- private List<ProvidedInterface> _provided;
- private List<RequiredInterface> _required;
+ private String context;
+ private String name;
+ private List<ProvidedInterface> provided;
+ private List<RequiredInterface> required;
/**
* Constructs the subsystem.
*/
protected AbstractComponent(String aName, List<ProvidedInterface> aProvided,
List<RequiredInterface> aRequired) {
- _remaining = new ThreadLocal<List<ProvidedInterface>>();
- _context = null;
- _name = aName;
- _provided = new ArrayList<ProvidedInterface>(aProvided);
- _required = new ArrayList<RequiredInterface>(aRequired);
+ remaining = new ThreadLocal<List<ProvidedInterface>>();
+ context = null;
+ name = aName;
+ provided = new ArrayList<ProvidedInterface>(aProvided);
+ required = new ArrayList<RequiredInterface>(aRequired);
}
/**
}
public AbstractComponent<Type> addProvidedInterface(ProvidedInterface aProvided) {
- _provided.add(aProvided);
+ provided.add(aProvided);
return this;
}
public AbstractComponent<Type> addRequiredInterface(RequiredInterface aRequired) {
- _required.add(aRequired);
+ required.add(aRequired);
return this;
}
@Override
public final String getName() {
- return _name;
+ return name;
}
@Override
public void addContext(String aContext) {
- if (_context == null) {
- _context = aContext;
+ if (context == null) {
+ context = aContext;
} else {
- _context = aContext + "." + _context;
+ context = aContext + "." + context;
}
}
@Override
public String getContext() {
- return _context;
+ return context;
}
@Override
public String getQualifiedName() {
- if (_context == null) {
+ if (context == null) {
return getName();
}
- return _context + "." + getName();
+ return context + "." + getName();
}
@Override
public final List<ProvidedInterface> getProvidedInterfaces() {
- return Collections.unmodifiableList(_provided);
+ return Collections.unmodifiableList(provided);
}
@Override
public final List<RequiredInterface> getRequiredInterfaces() {
- return Collections.unmodifiableList(_required);
+ return Collections.unmodifiableList(required);
}
@Override
public final Type start(Scope aScope) {
LOG.info("Initialization starting '" + getQualifiedName() + "'");
- List<ProvidedInterface> oldRemaining = _remaining.get();
- _remaining.set(new ArrayList<ProvidedInterface>(getProvidedInterfaces()));
+ List<ProvidedInterface> oldRemaining = remaining.get();
+ remaining.set(new ArrayList<ProvidedInterface>(getProvidedInterfaces()));
try {
Type runtime = doStart(aScope);
checkNotStartedInterfaces();
LOG.info("Initialization finished '" + getQualifiedName() + "'");
return runtime;
} finally {
- _remaining.set(oldRemaining);
+ remaining.set(oldRemaining);
}
}
private void checkNotStartedInterfaces() {
- if (_remaining.get().size() > 0) {
+ if (remaining.get().size() > 0) {
String notProvided = "";
- for (ProvidedInterface provided : _remaining.get()) {
+ for (ProvidedInterface provided : remaining.get()) {
notProvided += "\nComponent " + getQualifiedName()
+ " did not start interface " + provided;
}
Object aService, Scope aScope) {
LOG.info("Interface '" + getQualifiedName() + "."
+ aDescriptor.getName() + "' started.");
- if ( !_remaining.get().remove(aDescriptor) ) {
+ if ( !remaining.get().remove(aDescriptor) ) {
throw new SystemAssemblyException("Component '" + getQualifiedName() + "' started an unexpected interface '" +
aDescriptor + "' that was not registerd as a provided interface before");
}
*/
public class DefaultProvidedInterface implements ProvidedInterface {
- private String _name;
- private Class[] _interfaces;
+ private String name;
+ private Class[] interfaces;
/**
* Constructs the descriptor.
}
public DefaultProvidedInterface(String aName, Class[] aInterfaces) {
- _name = aName;
- _interfaces = Arrays.copyOf(aInterfaces, aInterfaces.length);
+ name = aName;
+ interfaces = Arrays.copyOf(aInterfaces, aInterfaces.length);
}
@Override
public String getName() {
- return _name;
+ return name;
}
@Override
public Class[] getInterfaceTypes() {
- return _interfaces;
+ return interfaces;
}
@Override
StringBuffer buf = new StringBuffer();
buf.append(getName());
buf.append(":");
- for (Class intf: _interfaces) {
+ for (Class intf: interfaces) {
buf.append(" " + intf.getName());
}
return buf.toString();
private String getEqualsRepresentation() {
List<String> result = new ArrayList<String>();
- for (Class cls: _interfaces) {
+ for (Class cls: interfaces) {
result.add(cls.getName());
}
Collections.sort(result);
public class DefaultRequiredInterface implements RequiredInterface {
- private String _name;
- private boolean _optional;
- private Class[] _required;
- private ProvidedInterface _provider;
+ private String name;
+ private boolean optional;
+ private Class[] required;
+ private ProvidedInterface provider;
public DefaultRequiredInterface(String aName, Class aInterface) {
this(aName, new Class[] { aInterface });
public DefaultRequiredInterface(String aName, Class[] aInterfaces, boolean aIsOptional) {
- _name = aName;
- _optional = aIsOptional;
- _required = aInterfaces;
+ name = aName;
+ optional = aIsOptional;
+ required = aInterfaces;
}
@Override
public String getName() {
- return _name;
+ return name;
}
@Override
public boolean isOptional() {
- return _optional;
+ return optional;
}
@Override
public boolean implementedBy(ProvidedInterface aDescriptor) {
Class[] provided = aDescriptor.getInterfaceTypes();
- for (Class required : _required) {
- if ( !serviceProvided(required, provided)) {
+ for (Class requiredIntf : required) {
+ if ( !serviceProvided(requiredIntf, provided)) {
return false;
}
}
@Override
public ProvidedInterface getProvider() {
- return _provider;
+ return provider;
}
@Override
public void setProvider(ProvidedInterface aProvider) {
assert aProvider != null;
assert implementedBy(aProvider);
- _provider = aProvider;
+ provider = aProvider;
}
@Override
return false;
}
DefaultRequiredInterface descr = (DefaultRequiredInterface)obj;
- if ( _required.length != descr._required.length ) {
+ if ( required.length != descr.required.length ) {
return false;
}
- String[] interfaces1 = new String[_required.length];
- String[] interfaces2 = new String[_required.length];
- for (int i = 0; i < _required.length; i++) {
- interfaces1[i] = _required[i].getName();
- interfaces2[i] = descr._required[i].getName();
+ String[] interfaces1 = new String[required.length];
+ String[] interfaces2 = new String[required.length];
+ for (int i = 0; i < required.length; i++) {
+ interfaces1[i] = required[i].getName();
+ interfaces2[i] = descr.required[i].getName();
}
Arrays.sort(interfaces1);
Arrays.sort(interfaces2);
@Override
public int hashCode() {
- return _required.hashCode();
+ return required.hashCode();
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("." + getName() + ":");
- for (Class intf: _required) {
+ for (Class intf: required) {
buf.append("." + intf.getName());
}
return buf.toString();
public class DefaultScope implements Scope {
- private List<Scope> _parents;
- private Map<String, Object> _properties;
- private Map<String, Object> _runtimes;
- private Map<ProvidedInterface, ProvidedInterfaceImplementation> _provided;
- private List<ProvidedInterface> _externallyProvided;
+ private List<Scope> parents;
+ private Map<String, Object> properties;
+ private Map<String, Object> runtimes;
+ private Map<ProvidedInterface, ProvidedInterfaceImplementation> provided;
+ private List<ProvidedInterface> externallyProvided;
public DefaultScope(List<ProvidedInterface>aExternallyProvided) {
this(aExternallyProvided.toArray(new ProvidedInterface[0]));
public DefaultScope(ProvidedInterface[] aExternallyProvided,
List<Scope> aParent) {
- _parents = new ArrayList<Scope>(aParent);
- _properties = new HashMap<String, Object>();
- _runtimes = new HashMap<String, Object>();
- _provided = new HashMap<ProvidedInterface, ProvidedInterfaceImplementation>();
- _externallyProvided = new ArrayList<ProvidedInterface>();
- _externallyProvided.addAll(Arrays.asList(aExternallyProvided));
+ parents = new ArrayList<Scope>(aParent);
+ properties = new HashMap<String, Object>();
+ runtimes = new HashMap<String, Object>();
+ provided = new HashMap<ProvidedInterface, ProvidedInterfaceImplementation>();
+ externallyProvided = new ArrayList<ProvidedInterface>();
+ externallyProvided.addAll(Arrays.asList(aExternallyProvided));
}
@Override
public List<ProvidedInterface> getProvidedInterfaces() {
- return Collections.unmodifiableList(_externallyProvided);
+ return Collections.unmodifiableList(externallyProvided);
}
@Override
public Object get(String aKey) {
- return _properties.get(aKey);
+ return properties.get(aKey);
}
@Override
public void put(String aKey, Object aValue) {
- _properties.put(aKey, aValue);
+ properties.put(aKey, aValue);
}
@Override
public void addRuntime(Component aComponent, Object aRuntime) {
- _runtimes.put(aComponent.getName(), aRuntime);
+ runtimes.put(aComponent.getName(), aRuntime);
}
@Override
public Object getRuntime(Component aComponent) {
- return _runtimes.get(aComponent.getName());
+ return runtimes.get(aComponent.getName());
}
@Override
public Object getRuntime(String aName) {
- return _runtimes.get(aName);
+ return runtimes.get(aName);
}
@Override
synchronized public void publishInterface(ProvidedInterface aInterface,
Object aImplementation) {
- _provided.put(aInterface, new ProvidedInterfaceImplementation(aInterface,
+ provided.put(aInterface, new ProvidedInterfaceImplementation(aInterface,
aImplementation));
}
if ( aInterface == null ) {
return null;
}
- ProvidedInterfaceImplementation provided = _provided.get(aInterface);
- if (provided == null) {
- for (Scope parent : _parents) {
+ ProvidedInterfaceImplementation providedIntf = provided.get(aInterface);
+ if (providedIntf == null) {
+ for (Scope parent : parents) {
T impl = parent.getInterfaceImplementation(aInterface, aType);
if ( impl != null ) {
return impl;
}
return null;
} else {
- return provided.getImplementation(aType);
+ return providedIntf.getImplementation(aType);
}
}
}
public class CompositeEdgeFilter implements EdgeFilter {
- private List<EdgeFilter> _filters;
+ private List<EdgeFilter> filters;
public CompositeEdgeFilter() {
- _filters = new ArrayList<EdgeFilter>();
+ filters = new ArrayList<EdgeFilter>();
}
public void add(EdgeFilter aFilter) {
- _filters.add(aFilter);
+ filters.add(aFilter);
}
@Override
public boolean isViolated(Edge aEdge) {
- for (EdgeFilter filter: _filters) {
+ for (EdgeFilter filter: filters) {
if ( filter.isViolated(aEdge) ) {
return true;
}
*/
public class DefaultEdge implements Edge {
- private Node _from;
- private Node _to;
+ private Node from;
+ private Node to;
public DefaultEdge(Node aFrom, Node aTo) {
- _from = aFrom;
- _to = aTo;
+ from = aFrom;
+ to = aTo;
}
@Override
public Node getFrom() {
- return _from;
+ return from;
}
@Override
public Node getTo() {
- return _to;
+ return to;
}
@Override
public String toString() {
- return "Edge(" + _from.getName() + ", " + _to.getName() + ")";
+ return "Edge(" + from.getName() + ", " + to.getName() + ")";
}
}
*/
public class DefaultNode implements Node {
- private String _name;
+ private String name;
/**
* Constructs the node.
* @param aName Node name.
*/
public DefaultNode(String aName) {
- _name = aName;
+ name = aName;
}
/**
*/
@Override
public String getName() {
- return _name;
+ return name;
}
@Override
return false;
}
Node node = (Node)aObj;
- return _name.equals(node.getName());
+ return name.equals(node.getName());
}
@Override
public int hashCode() {
- return _name.hashCode();
+ return name.hashCode();
}
}
void execute(FromType aFrom, ToType aTo);
}
- private Class<FromType> _fromType;
- private Class<ToType> _toType;
+ private Class<FromType> fromType;
+ private Class<ToType> toType;
public EdgeSelector(Class<FromType> aFrom, Class<ToType> aTo) {
- _fromType = aFrom;
- _toType = aTo;
+ fromType = aFrom;
+ toType = aTo;
}
public void execute(Selector<FromType,ToType> aSelector, Edge aEdge) {
- if ( _fromType.isInstance(aEdge.getFrom()) && _toType.isInstance(aEdge.getTo())) {
+ if ( fromType.isInstance(aEdge.getFrom()) && toType.isInstance(aEdge.getTo())) {
aSelector.execute((FromType)aEdge.getFrom(), (ToType)aEdge.getTo());
}
}
*/
public class Graph {
- private List<Node> _nodes;
- private List<Edge> _edges;
+ private List<Node> nodes;
+ private List<Edge> edges;
/**
* Constructs the graph.
*/
public Graph() {
- _nodes = new ArrayList<Node>();
- _edges = new ArrayList<Edge>();
+ nodes = new ArrayList<Node>();
+ edges = new ArrayList<Edge>();
}
/**
* using <code>equals</code>.
*/
public void addNode(Node aNode) {
- if (_nodes.contains(aNode)) {
+ if (nodes.contains(aNode)) {
throw new IllegalArgumentException("Node '" + aNode.getName()
+ "' already exists");
}
- _nodes.add(aNode);
+ nodes.add(aNode);
}
/**
* @return Node or null if not found.
*/
public Node findNode(String aName) {
- for (Node node : _nodes) {
+ for (Node node : nodes) {
if (node.getName().equals(aName)) {
return node;
}
+ aNode.getName()
+ "' because it is connected to one or more edges");
}
- return _nodes.remove(aNode);
+ return nodes.remove(aNode);
}
/**
* {@link #equals(Object)} is already a part of the graph.
*/
public void addEdge(Edge aEdge) {
- if (_edges.contains(aEdge)) {
+ if (edges.contains(aEdge)) {
throw new IllegalArgumentException("Edge '" + aEdge
+ "' already exists");
}
- if (!_nodes.contains(aEdge.getFrom())) {
+ if (!nodes.contains(aEdge.getFrom())) {
throw new IllegalArgumentException("From node '" + aEdge.getFrom()
+ "' from edge '" + aEdge + "' is not part of the graph");
}
- if (!_nodes.contains(aEdge.getTo())) {
+ if (!nodes.contains(aEdge.getTo())) {
throw new IllegalArgumentException("To node '" + aEdge.getTo()
+ "' from edge '" + aEdge + "' is not part of the graph");
}
- _edges.add(aEdge);
+ edges.add(aEdge);
}
/**
* @return True if the edge was removed.
*/
public boolean removeEdge(Edge aEdge) {
- return _edges.remove(aEdge);
+ return edges.remove(aEdge);
}
/**
* @return Copy of the list of nodes of the graph.
*/
public List<Node> getNodes() {
- return new ArrayList<Node>(_nodes);
+ return new ArrayList<Node>(nodes);
}
/**
* @return Copy of the list of edges of the graph.
*/
public List<Edge> getEdges() {
- return new ArrayList<Edge>(_edges);
+ return new ArrayList<Edge>(edges);
}
/**
* @param aFactory Edge factory.
*/
public void extend(EdgeFactory aFactory) {
- for (Node from : _nodes) {
- for (Node to : _nodes) {
- _edges.addAll(aFactory.create(from, to));
+ for (Node from : nodes) {
+ for (Node to : nodes) {
+ edges.addAll(aFactory.create(from, to));
}
}
}
* @param aFilter Filter to apply.
*/
public void applyFilter(EdgeFilter aFilter) {
- for (Iterator<Edge> edge = _edges.iterator(); edge.hasNext(); ) {
+ for (Iterator<Edge> edge = edges.iterator(); edge.hasNext(); ) {
if (aFilter.isViolated(edge.next())) {
edge.remove();
}
*/
public List<Edge> findOutgoing(Node aNode) {
List<Edge> result = new ArrayList<Edge>();
- for (Edge edge : _edges) {
+ for (Edge edge : edges) {
if (edge.getFrom().getName().equals(aNode.getName())) {
result.add(edge);
}
*/
public List<Edge> findIncoming(Node aNode) {
List<Edge> result = new ArrayList<Edge>();
- for (Edge edge : _edges) {
+ for (Edge edge : edges) {
if (edge.getTo().getName().equals(aNode.getName())) {
result.add(edge);
}
*/
public class CheckExternallyProvidedVisitor implements Visitor {
- private Graph _graph;
+ private Graph graph;
/**
* Constructs the visitor.
* @param aGraph Component graph.
*/
public CheckExternallyProvidedVisitor(Graph aGraph) {
- _graph = aGraph;
+ graph = aGraph;
}
@Override
public void visitNode(Node aNode) {
if ( aNode instanceof ExternalProvidedInterfaceNode) {
ExternalProvidedInterfaceNode provided = (ExternalProvidedInterfaceNode) aNode;
- List<Edge> edges = _graph.findOutgoing(provided);
+ List<Edge> edges = graph.findOutgoing(provided);
if ( edges.size() > 2 ) {
createDuplicateException("External provided interfaces has multiple internal matches", aNode, edges);
}
private Log LOG = LogFactory.getLog(CheckExternallyRequiredVisitor.class);
- private Graph _graph;
+ private Graph graph;
public CheckExternallyRequiredVisitor(Graph aGraph) {
- _graph = aGraph;
+ graph = aGraph;
}
@Override
+ ": External required interface is not provided");
}
- List<Edge> edges = _graph.findIncoming(aNode);
+ List<Edge> edges = graph.findIncoming(aNode);
if (edges.isEmpty()) {
LOG.warn(aNode + ": Superfluous required interface");
*/
public class CheckRequiredProvidedMultiplicityVisitor implements Visitor {
- private Graph _graph;
+ private Graph graph;
public CheckRequiredProvidedMultiplicityVisitor(Graph aGraph) {
- _graph = aGraph;
+ graph = aGraph;
}
@Override
public void visitNode(Node aNode) {
if (aNode instanceof RequiredInterfaceNode) {
RequiredInterfaceNode required = (RequiredInterfaceNode) aNode;
- List<Edge> edges = _graph.findOutgoing(aNode);
+ List<Edge> edges = graph.findOutgoing(aNode);
if (edges.size() > 1) {
createDuplicateException("Multiple providers of required interface found", aNode, edges);
}
+ ": mandatpory required interface not provided by other components started earlier");
}
} else if ( aNode instanceof ExternalProvidedInterfaceNode) {
- List<Edge> edges = _graph.findOutgoing(aNode);
+ List<Edge> edges = graph.findOutgoing(aNode);
if ( edges.size() > 1) {
createDuplicateException("multiple internal matches for externally provided interface", aNode, edges);
}
*/
public class CheckStartupDependenciesVisitor implements Visitor {
- private Graph _graph;
- private List<Node> _available;
+ private Graph graph;
+ private List<Node> available;
/**
* Constructs the visitor.
* @param aGraph Graph.
*/
public CheckStartupDependenciesVisitor(Graph aGraph) {
- _graph = aGraph;
- _available = new ArrayList<Node>();
+ graph = aGraph;
+ available = new ArrayList<Node>();
}
@Override
@Override
public void visitNode(Node aNode) {
- List<Edge> edges = _graph.findOutgoing(aNode);
+ List<Edge> edges = graph.findOutgoing(aNode);
// check dependencies.
for (Edge edge: edges) {
Node dep = edge.getTo();
- if ( !_available.contains(dep)) {
+ if ( !available.contains(dep)) {
throw new SystemAssemblyException(aNode + ": required dependency '" + dep + "' was not started");
}
}
- _available.add(aNode);
+ available.add(aNode);
}
}
*/
public class ComponentGraph extends Graph {
- private boolean _isLinked;
- private CompositeEdgeFilter _edgeFilter;
+ private boolean isLinked;
+ private CompositeEdgeFilter edgeFilter;
/**
* Constructs an empty component graph.
*/
public ComponentGraph() {
- _isLinked = false;
- _edgeFilter = new CompositeEdgeFilter();
+ isLinked = false;
+ edgeFilter = new CompositeEdgeFilter();
}
/**
*/
public void validate() {
extend(new RequiredProvidedEdgeFactory());
- applyFilter(_edgeFilter);
+ applyFilter(edgeFilter);
accept(new CheckRequiredProvidedMultiplicityVisitor(this));
accept(new CheckExternallyRequiredVisitor(this));
accept(new CheckExternallyProvidedVisitor(this));
* model based on the graph model.
*/
public void link() {
- if ( _isLinked ) {
+ if ( isLinked ) {
return;
}
accept(new LinkVisitor());
- _isLinked = true;
+ isLinked = true;
}
/**
}
public void addEdgeFilter(CompositeEdgeFilter aEdgeFilter) {
- _edgeFilter.add(aEdgeFilter);
+ edgeFilter.add(aEdgeFilter);
}
}
*/
public class ComponentNode implements Node {
- private Component<?> _component;
+ private Component<?> component;
public ComponentNode(Component<?> aComponent) {
- _component = aComponent;
+ component = aComponent;
}
@Override
public String getName() {
- return _component.getQualifiedName();
+ return component.getQualifiedName();
}
public Component<?> getComponent() {
- return _component;
+ return component;
}
}
*/
public class ConnectExternalProvidedProvidedFilter implements EdgeFilter {
- private String _externalProvided;
- private String _component;
- private String _provided;
+ private String externalProvided;
+ private String component;
+ private String provided;
public ConnectExternalProvidedProvidedFilter(String aExternalProvided, String aComponent,
String aProvided) {
- _externalProvided = aExternalProvided;
- _component = aComponent;
- _provided = aProvided;
- if ( _externalProvided == null ) {
+ externalProvided = aExternalProvided;
+ component = aComponent;
+ provided = aProvided;
+ if ( externalProvided == null ) {
throw new IllegalArgumentException("External provided interface name must be specified.");
}
- if ( _component == null ) {
+ if ( component == null ) {
throw new IllegalArgumentException("Component name must be specified");
}
- if ( _provided == null ) {
+ if ( provided == null ) {
throw new IllegalArgumentException("Provided interface name of internal component must be specified");
}
}
private boolean isViolated(ExternalProvidedInterfaceNode aFrom,
ProvidedInterfaceNode aTo) {
- if ( !aFrom.getName().equals(_externalProvided)) {
+ if ( !aFrom.getName().equals(externalProvided)) {
return false; // wrong provided interface.
}
- if ( aTo.getComponent().getName().equals(_component) &&
- aTo.getProvided().getName().equals(_provided) ) {
+ if ( aTo.getComponent().getName().equals(component) &&
+ aTo.getProvided().getName().equals(provided) ) {
return false; // ok
}
return true;
*/
public class ConnectRequiredExternallyRequiredEdgeFilter implements EdgeFilter {
- private String _client;
- private String _required;
- private String _externalRequired;
+ private String client;
+ private String required;
+ private String externalRequired;
public ConnectRequiredExternallyRequiredEdgeFilter(String aClient, String aRequired,
String aExternalRequired) {
- _client = aClient;
- _required = aRequired;
- _externalRequired = aExternalRequired;
- if ( _client == null ) {
+ client = aClient;
+ required = aRequired;
+ externalRequired = aExternalRequired;
+ if ( client == null ) {
throw new IllegalArgumentException("Client component must be specified");
}
- if ( _required == null ) {
+ if ( required == null ) {
throw new IllegalArgumentException("Required interface must be specified");
}
- if ( _externalRequired == null ) {
+ if ( externalRequired == null ) {
throw new IllegalArgumentException("External required interface must be specified");
}
}
private boolean isViolated(RequiredInterfaceNode aFrom,
ExternalRequiredInterfaceNode aTo) {
- if ( !aFrom.getComponent().getName().equals(_client)) {
+ if ( !aFrom.getComponent().getName().equals(client)) {
return false; // wrong component.
}
- if ( !(_required == null || aFrom.getRequired().getName().equals(_required))) {
+ if ( !(required == null || aFrom.getRequired().getName().equals(required))) {
return false; // wrong interface
}
- if ( !aTo.getRequired().getName().equals(_externalRequired)) {
+ if ( !aTo.getRequired().getName().equals(externalRequired)) {
return true; // wrong externally required interface.
}
*/
public class ConnectRequiredProvidedEdgeFilter implements EdgeFilter {
- private String _client;
- private String _required;
- private String _server;
- private String _provided;
+ private String client;
+ private String required;
+ private String server;
+ private String provided;
public ConnectRequiredProvidedEdgeFilter(String aClient, String aRequired,
String aServer, String aProvided) {
- _client = aClient;
- _required = aRequired;
- _server = aServer;
- _provided = aProvided;
- if ( _client == null ) {
+ client = aClient;
+ required = aRequired;
+ server = aServer;
+ provided = aProvided;
+ if ( client == null ) {
throw new IllegalArgumentException("Client component must be specified");
}
}
private boolean isViolated(RequiredInterfaceNode aFrom,
ProvidedInterfaceNode aTo) {
- if (_client.equals(aFrom.getComponent().getName())
- && (_required == null || _required.equals(aFrom.getRequired()
+ if (client.equals(aFrom.getComponent().getName())
+ && (required == null || required.equals(aFrom.getRequired()
.getName()))) {
// From part matches.
- if ( _server == null ) {
+ if ( server == null ) {
return true; // all connections are eliminated
}
- if (_server.equals(aTo.getComponent().getName())
- && (_provided == null || _provided.equals(aTo.getProvided()
+ if (server.equals(aTo.getComponent().getName())
+ && (provided == null || provided.equals(aTo.getProvided()
.getName()))) {
// to part matches also
return false;
*/
public class ExternalProvidedInterfaceNode implements Node {
- private Component _component;
- private ProvidedInterface _provided;
+ private Component component;
+ private ProvidedInterface provided;
public ExternalProvidedInterfaceNode(Component aComponent, ProvidedInterface aProvided) {
- _component = aComponent;
- _provided = aProvided;
+ component = aComponent;
+ provided = aProvided;
}
@Override
public String getName() {
- return _provided.getName();
+ return provided.getName();
}
public Component getComponent() {
- return _component;
+ return component;
}
public ProvidedInterface getProvided() {
- return _provided;
+ return provided;
}
@Override
public String toString() {
- return _component.getQualifiedName() + ":" + _provided;
+ return component.getQualifiedName() + ":" + provided;
}
}
*/
public class ExternalRequiredInterfaceNode implements Node {
- private Component _component;
- private RequiredInterface _required;
+ private Component component;
+ private RequiredInterface required;
public ExternalRequiredInterfaceNode(Component aComponent, RequiredInterface aRequired) {
- _component = aComponent;
- _required = aRequired;
+ component = aComponent;
+ required = aRequired;
}
@Override
public String getName() {
- return _required.getName();
+ return required.getName();
}
public Component getComponent() {
- return _component;
+ return component;
}
public RequiredInterface getRequired() {
- return _required;
+ return required;
}
@Override
public String toString() {
- return _component.getQualifiedName() + ":" + _required;
+ return component.getQualifiedName() + ":" + required;
}
}
*/
public class ProvidedInterfaceNode implements Node {
- private Component _component;
- private ProvidedInterface _provided;
+ private Component component;
+ private ProvidedInterface provided;
public ProvidedInterfaceNode(Component aComponent, ProvidedInterface aProvided) {
- _component = aComponent;
- _provided = aProvided;
+ component = aComponent;
+ provided = aProvided;
}
@Override
public String getName() {
- return _component.getQualifiedName() + ":" + _provided.getName();
+ return component.getQualifiedName() + ":" + provided.getName();
}
public ProvidedInterface getProvided() {
- return _provided;
+ return provided;
}
public Component getComponent() {
- return _component;
+ return component;
}
@Override
public String toString() {
- return _component.getQualifiedName() + ":" + _provided;
+ return component.getQualifiedName() + ":" + provided;
}
}
*/
public class RequiredInterfaceNode implements Node {
- private Component _component;
- private RequiredInterface _required;
+ private Component component;
+ private RequiredInterface required;
public RequiredInterfaceNode(Component aComponent, RequiredInterface aRequired) {
- _component = aComponent;
- _required = aRequired;
+ component = aComponent;
+ required = aRequired;
}
@Override
public String getName() {
- return _component.getQualifiedName() + ":" + _required.getName();
+ return component.getQualifiedName() + ":" + required.getName();
}
public RequiredInterface getRequired() {
- return _required;
+ return required;
}
public Component getComponent() {
- return _component;
+ return component;
}
@Override
public String toString() {
- return _component.getQualifiedName() + ":" + _required;
+ return component.getQualifiedName() + ":" + required;
}
}
public class AdapterTestCase extends TestCase {
- protected Scope _scope;
+ protected Scope scope;
static EventTracker<String> EVENT_TRACKER;
@Override
protected void setUp() throws Exception {
super.setUp();
EVENT_TRACKER = new EventTracker<String>();
- _scope = new DefaultScope(new ProvidedInterface[0]);
+ scope = new DefaultScope(new ProvidedInterface[0]);
}
}
required.get(0).setProvider(provided);
- _scope.publishInterface(provided, "hello");
- classConfig.create(_scope);
+ scope.publishInterface(provided, "hello");
+ classConfig.create(scope);
AssertionUtils.assertEquals(new String[] { "x1(hello)" },
AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
required.get(0).setProvider(providedBoolean);
required.get(1).setProvider(providedHost);
- _scope.publishInterface(providedBoolean, true);
- _scope.publishInterface(providedHost, "host.name.org");
+ scope.publishInterface(providedBoolean, true);
+ scope.publishInterface(providedHost, "host.name.org");
- Object obj = classConfig.create(_scope);
+ Object obj = classConfig.create(scope);
assertTrue(obj instanceof X7);
X7 x7 = (X7)obj;
assertNotNull(x7.getBoolean());
assertNull(x7.getHost());
assertNull(x7.getPort());
- classConfig.inject(_scope, obj);
+ classConfig.inject(scope, obj);
assertEquals("host.name.org", x7.getHost());
assertEquals(10, x7.getPort().intValue());
required.get(0).setProvider(provided);
- _scope.publishInterface(provided, "hello");
- config.create(_scope);
+ scope.publishInterface(provided, "hello");
+ config.create(scope);
AssertionUtils.assertEquals(new String[] { "x1(hello)" }, AdapterTestCase.EVENT_TRACKER
.getEvents(Thread.currentThread()).toArray());
assertEquals(1, required.size());
required.get(0).setProvider(provided);
- _scope.publishInterface(provided, "hello");
- config.create(_scope);
+ scope.publishInterface(provided, "hello");
+ config.create(scope);
AssertionUtils.assertEquals(new String[] { "x2(hello)" }, AdapterTestCase.EVENT_TRACKER
.getEvents(Thread.currentThread()).toArray());
.greedy();
config.getParameters().setValue(0, "bla");
- config.create(_scope);
+ config.create(scope);
AssertionUtils.assertEquals(new String[] { "x1(bla)" }, AdapterTestCase.EVENT_TRACKER
.getEvents(Thread.currentThread()).toArray());
assertEquals(1, required.size());
required.get(0).setProvider(provided);
- _scope.publishInterface(provided, "hello");
- config.create(_scope);
+ scope.publishInterface(provided, "hello");
+ config.create(scope);
AssertionUtils.assertEquals(new String[] { "x1(hello)" }, AdapterTestCase.EVENT_TRACKER
.getEvents(Thread.currentThread()).toArray());
config.getParameters().setOptional(0);
assertTrue(config.getRequiredInterfaces().get(0).isOptional());
- config.create(_scope);
+ config.create(scope);
AssertionUtils.assertEquals(new String[] { "x1(null)" }, AdapterTestCase.EVENT_TRACKER
.getEvents(Thread.currentThread()).toArray());
required.get(0).setProvider(provided);
- _scope.publishInterface(provided, "hello");
- config.create(_scope);
+ scope.publishInterface(provided, "hello");
+ config.create(scope);
AssertionUtils.assertEquals(new String[] { "x3(hello)" }, AdapterTestCase.EVENT_TRACKER
.getEvents(Thread.currentThread()).toArray());
ProvidedInterface provided = new DefaultProvidedInterface("janse",
String.class);
required.get(0).setProvider(provided);
- _scope.publishInterface(provided, "hello");
+ scope.publishInterface(provided, "hello");
X5 obj = new X5();
assertNull(obj.getValue());
- config.inject(_scope, obj);
+ config.inject(scope, obj);
assertEquals("hello", obj.getValue());
}
"janse", String.class);
assertTrue(required.get(0).implementedBy(providedString));
required.get(0).setProvider(providedString);
- _scope.publishInterface(providedString, "hello");
+ scope.publishInterface(providedString, "hello");
ProvidedInterface providedInt = new DefaultProvidedInterface("xxx",
Integer.class);
assertTrue(required.get(1).implementedBy(providedInt));
required.get(1).setProvider(providedInt);
- _scope.publishInterface(providedInt, 100);
+ scope.publishInterface(providedInt, 100);
X5 obj = new X5();
assertNull(obj.getValue());
assertNull(obj.getXyz());
- config.inject(_scope, obj);
+ config.inject(scope, obj);
assertEquals("hello", obj.getValue());
assertEquals(100, obj.getXyz().intValue());
}
"janse", Boolean.class);
assertTrue(required.get(0).implementedBy(providedBoolean));
required.get(0).setProvider(providedBoolean);
- _scope.publishInterface(providedBoolean, true);
+ scope.publishInterface(providedBoolean, true);
ProvidedInterface providedString = new DefaultProvidedInterface(
"janse", String.class);
assertTrue(required.get(1).implementedBy(providedString));
required.get(1).setProvider(providedString);
- _scope.publishInterface(providedString, "hello");
+ scope.publishInterface(providedString, "hello");
ProvidedInterface providedInt = new DefaultProvidedInterface("xxx",
Integer.class);
assertTrue(required.get(2).implementedBy(providedInt));
required.get(2).setProvider(providedInt);
- _scope.publishInterface(providedInt, 100);
+ scope.publishInterface(providedInt, 100);
X9 obj = new X9();
assertNull(obj.getValue());
assertNull(obj.getXyz());
assertFalse(obj.isFlag());
- config.inject(_scope, obj);
+ config.inject(scope, obj);
assertEquals("hello", obj.getValue());
assertEquals(100, obj.getXyz().intValue());
assertTrue(obj.isFlag());
ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
String.class);
required.get(0).setProvider(provided0);
- _scope.publishInterface(provided0, "hello");
+ scope.publishInterface(provided0, "hello");
ProvidedInterface provided1 = new DefaultProvidedInterface("port",
Integer.class);
required.get(1).setProvider(provided1);
- _scope.publishInterface(provided1, 10);
+ scope.publishInterface(provided1, 10);
X6 obj = new X6();
assertNull(obj.getHost());
assertNull(obj.getPort());
- config.inject(_scope, obj);
+ config.inject(scope, obj);
assertEquals("hello", obj.getHost());
assertEquals(10, obj.getPort().intValue());
}
ProvidedInterface provided = new DefaultProvidedInterface("janse",
String.class);
required.get(0).setProvider(provided);
- _scope.publishInterface(provided, "hello");
+ scope.publishInterface(provided, "hello");
final X6 obj = new X6();
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
@Override
public void run() throws Exception {
- config.inject(_scope, obj);
+ config.inject(scope, obj);
}
}, IllegalArgumentException.class);
}
X5 obj = new X5();
assertNull(obj.getValue());
- config.inject(_scope, obj);
+ config.inject(scope, obj);
assertEquals("bladibla", obj.getValue());
}
assertNull(obj.getHost());
assertNull(obj.getPort());
- config.inject(_scope, obj);
+ config.inject(scope, obj);
assertNull(obj.getHost());
assertNull(obj.getPort());
ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
String.class);
required.get(0).setProvider(provided0);
- _scope.publishInterface(provided0, "hello");
+ scope.publishInterface(provided0, "hello");
X6 obj = new X6();
assertNull(obj.getHost());
assertNull(obj.getPort());
- config.inject(_scope, obj);
+ config.inject(scope, obj);
assertEquals("hello", obj.getHost());
assertNull(obj.getPort());
}
ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
String.class);
required.get(0).setProvider(provided0);
- _scope.publishInterface(provided0, "hello");
+ scope.publishInterface(provided0, "hello");
X6 obj = new X6();
assertNull(obj.getHost());
assertNull(obj.getPort());
- config.inject(_scope, obj);
+ config.inject(scope, obj);
assertEquals("hello", obj.getHost());
assertNull(obj.getPort());
}
ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
String.class);
required.get(0).setProvider(provided0);
- _scope.publishInterface(provided0, "hello");
+ scope.publishInterface(provided0, "hello");
X6 obj = new X6();
assertNull(obj.getHost());
assertNull(obj.getPort());
- config.inject(_scope, obj);
+ config.inject(scope, obj);
assertEquals("hello", obj.getHost());
assertNull(obj.getPort());
}
ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
String.class);
required.get(0).setProvider(provided0);
- _scope.publishInterface(provided0, "hello");
+ scope.publishInterface(provided0, "hello");
X6 obj = new X6();
assertNull(obj.getHost());
assertNull(obj.getPort());
- config.inject(_scope, obj);
+ config.inject(scope, obj);
assertEquals("hello", obj.getHost());
assertNull(obj.getPort());
}
public class X4 {
- private X1 _x1;
+ private X1 x1;
public X4(X1 aX1) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x4(x1)");
- _x1 = aX1;
+ x1 = aX1;
}
public X1 getX1() {
- return _x1;
+ return x1;
}
}
public class X5 {
- private String _value;
- private Integer _xyz;
+ private String value;
+ private Integer xyz;
public X5() {
public void setValue(String aValue) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x5.setValue(" + aValue + ")");
- _value = aValue;
+ value = aValue;
}
public String getValue() {
- return _value;
+ return value;
}
public void doSomething() {
}
private void setXyz(int aXyz) {
- _xyz = aXyz;
+ xyz = aXyz;
}
public Integer getXyz() {
- return _xyz;
+ return xyz;
}
}
\ No newline at end of file
public class X6 {
- private String _host;
- private Integer _port;
+ private String host;
+ private Integer port;
public X6() {
}
public Integer getPort() {
- return _port;
+ return port;
}
public void setPort(Integer aPort) {
- _port = aPort;
+ port = aPort;
}
public String getHost() {
- return _host;
+ return host;
}
public void setHost(String aHost) {
- _host = aHost;
+ host = aHost;
}
}
\ No newline at end of file
public class X7 {
- private String _host;
- private Integer _port;
- private Boolean _boolean;
+ private String host;
+ private Integer port;
+ private Boolean flag;
public X7(Boolean aBoolean) {
- _boolean = aBoolean;
+ flag = aBoolean;
}
public Boolean getBoolean() {
- return _boolean;
+ return flag;
}
public Integer getPort() {
- return _port;
+ return port;
}
public void setPort(Integer aPort) {
- _port = aPort;
+ port = aPort;
}
public String getHost() {
- return _host;
+ return host;
}
public void setHost(String aHost) {
- _host = aHost;
+ host = aHost;
}
}
\ No newline at end of file
public class X8 {
- private X1 _x1;
- private X4 _x4;
+ private X1 x1;
+ private X4 x4;
public X8(X1 aX1) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x8(x1)");
- _x1 = aX1;
+ x1 = aX1;
}
public void setX4(X4 aX4) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x8.setX4(x4)");
- _x4 = aX4;
+ x4 = aX4;
}
public X4 getX4() {
- return _x4;
+ return x4;
}
public X1 getX1() {
- return _x1;
+ return x1;
}
}
public class X9 extends X5 {
- private boolean _flag;
+ private boolean flag;
public X9() {
}
public boolean isFlag() {
- return _flag;
+ return flag;
}
public void setFlag(boolean aFlag) {
- _flag = aFlag;
+ flag = aFlag;
}
}
private static ProvidedInterface DB_PROPS = new DefaultProvidedInterface("dbProps", Properties.class);
- private Database _database;
+ private Database database;
public DatabaseComponent(String aName, Database aDatabase) {
super(aName);
- _database = aDatabase;
+ database = aDatabase;
addProvidedInterface(DB_PROPS);
}
@Override
protected Database doStart(Scope aScope) {
- _database.start();
+ database.start();
Properties props = new Properties();
- if ( _database instanceof DerbyDatabase ) {
+ if ( database instanceof DerbyDatabase ) {
props.put("database.type", DatabaseType.DERBY.toString());
} else {
- throw new IllegalArgumentException("Unknown database type " + _database);
+ throw new IllegalArgumentException("Unknown database type " + database);
}
- //props.put("database.driver", _database.getDriverClassName());
- props.put("database.url", _database.getJdbcUrl());
- props.put("database.username", _database.getUsername());
- props.put("database.password", _database.getPassword());
+ //props.put("database.driver", database.getDriverClassName());
+ props.put("database.url", database.getJdbcUrl());
+ props.put("database.username", database.getUsername());
+ props.put("database.password", database.getPassword());
addInterface(DB_PROPS, props, aScope);
- return _database;
+ return database;
}
@Override
protected void doStop(Database aRuntime) {
- _database.stop();
+ database.stop();
}
}
return required(aOptional, "");
}
- private EventTracker<String> _tracker;
- private String _string;
- private Integer _integer;
- private double _random;
+ private EventTracker<String> tracker;
+ private String string;
+ private Integer integer;
+ private double random;
public Application() {
this("application");
public Application(String aName, String aPrefix) {
super(aName, new ProvidedInterface[0], required(false,
aPrefix));
- _random = Math.random();
+ random = Math.random();
}
public Application(boolean aIsOptinal) {
public Application(EventTracker<String> aTracker) {
this();
- _tracker = aTracker;
+ tracker = aTracker;
}
@Override
public Object doStart(Scope aScope) {
track("start." + getName());
- _string = aScope.getInterfaceImplementation(getRequiredInterfaces()
+ string = aScope.getInterfaceImplementation(getRequiredInterfaces()
.get(0).getProvider(), String.class);
- _integer = aScope.getInterfaceImplementation(getRequiredInterfaces()
+ integer = aScope.getInterfaceImplementation(getRequiredInterfaces()
.get(1).getProvider(), Integer.class);
- return _random;
+ return random;
}
public String getString() {
- return _string;
+ return string;
}
public Integer getInteger() {
- return _integer;
+ return integer;
}
@Override
public void doStop(Object aRuntime) {
track("stop." + getName());
- if (_random != (Double) aRuntime) {
+ if (random != (Double) aRuntime) {
throw new IllegalArgumentException("Wrong runtime: expected "
- + _random + " but got " + aRuntime);
+ + random + " but got " + aRuntime);
}
}
private void track(String aString) {
- if (_tracker == null) {
+ if (tracker == null) {
return;
}
- _tracker.eventOccurred(aString);
+ tracker.eventOccurred(aString);
}
}
public class ContainerTest extends TestCase {
- private EventTracker<String> _tracker;
+ private EventTracker<String> tracker;
@Override
protected void setUp() throws Exception {
super.setUp();
- _tracker = new EventTracker<String>();
+ tracker = new EventTracker<String>();
}
private static class MyMultiple implements Serializable, Runnable {
}
public void testEnvironmentApplication() {
- Environment environment = new Environment(_tracker);
- Application application = new Application(_tracker);
+ Environment environment = new Environment(tracker);
+ Application application = new Application(tracker);
Container container = new Container("root", new Component[] {
environment, application }, new ProvidedInterface[0],
new RequiredInterface[0]);
Scope scope = container.start();
assertTrue(container.isSealed());
AssertionUtils.assertEquals(new String[] { "start.environment",
- "start.application" }, _tracker.getEvents(
+ "start.application" }, tracker.getEvents(
Thread.currentThread()).toArray(new String[0]));
assertEquals(0, scope.getProvidedInterfaces().size());
}
public void testEnvironmentApplicationSimpleConstructor() {
- Environment environment = new Environment(_tracker);
- Application application = new Application(_tracker);
+ Environment environment = new Environment(tracker);
+ Application application = new Application(tracker);
Container container = new Container("root").addComponent(environment)
.addComponent(application);
Scope scope = container.start();
AssertionUtils.assertEquals(new String[] { "start.environment",
- "start.application" }, _tracker.getEvents(
+ "start.application" }, tracker.getEvents(
Thread.currentThread()).toArray(new String[0]));
assertEquals(0, scope.getProvidedInterfaces().size());
}
public void testComposite() {
- Component<?> environment = new Environment(_tracker);
- Component<?> application = new Application(_tracker);
- assertEquals(0, _tracker.getEventCount());
+ Component<?> environment = new Environment(tracker);
+ Component<?> application = new Application(tracker);
+ assertEquals(0, tracker.getEventCount());
Container system = new Container("all", new Component[] { environment,
application }, new ProvidedInterface[0],
assertEquals(0, provided.size());
AssertionUtils.assertEquals(new String[] { "start.environment",
- "start.application" }, _tracker.getEvents(
+ "start.application" }, tracker.getEvents(
Thread.currentThread()).toArray(new String[0]));
- _tracker.clear();
+ tracker.clear();
system.stop(runtime);
AssertionUtils.assertEquals(new String[] { "stop.application",
- "stop.environment" }, _tracker
+ "stop.environment" }, tracker
.getEvents(Thread.currentThread()).toArray(new String[0]));
}
public void testEnvironmentApplicationRollbackOnException()
throws Exception {
- Environment environment = new Environment(_tracker);
+ Environment environment = new Environment(tracker);
Application application = new Application() {
@Override
public Object doStart(Scope aScope) {
container.start();
} catch (RuntimeException e) {
AssertionUtils.assertEquals(new String[] { "start.environment",
- "stop.environment" }, _tracker.getEvents(
+ "stop.environment" }, tracker.getEvents(
Thread.currentThread()).toArray(new String[0]));
return;
}
public void testEnvironmentApplicationRollbackOnExceptionWithExceptionOnStop()
throws Exception {
- Environment environment = new Environment(_tracker);
+ Environment environment = new Environment(tracker);
// Application 1 will throw an exception while stopping.
Application application1 = new Application("app1") {
@Override
container.start();
} catch (RuntimeException e) {
AssertionUtils.assertEquals(new String[] { "start.environment",
- "stop.environment" }, _tracker.getEvents(
+ "stop.environment" }, tracker.getEvents(
Thread.currentThread()).toArray(new String[0]));
return;
}
}
public void testProvidedInterfaces() {
- Environment env = new Environment(_tracker);
+ Environment env = new Environment(tracker);
Container envcontainer = new Container("0").addComponent(env)
.addProvidedInterface(
new DefaultProvidedInterface("string", String.class))
Scope scope = envcontainer.start();
AssertionUtils.assertEquals(new String[] { "start.environment" },
- _tracker.getEvents(Thread.currentThread()).toArray(
+ tracker.getEvents(Thread.currentThread()).toArray(
new String[0]));
envcontainer.stop(scope);
}
public void testCoupleTwoContainers() {
- Environment env = new Environment(_tracker);
+ Environment env = new Environment(tracker);
Container envcontainer = new Container("0").addComponent(env)
.addProvidedInterface(
new DefaultProvidedInterface("string", String.class))
.addProvidedInterface(
new DefaultProvidedInterface("integer", Integer.class));
- Application app = new Application(_tracker);
+ Application app = new Application(tracker);
Container appcontainer = new Container("1").addComponent(app)
.addRequiredInterface(
new DefaultRequiredInterface("string", String.class))
top.start();
AssertionUtils.assertEquals(new String[] { "start.environment",
- "start.application" }, _tracker.getEvents(
+ "start.application" }, tracker.getEvents(
Thread.currentThread()).toArray(new String[0]));
}
private static int COUNT = 0;
- private EventTracker<String> _tracker;
- private double _random;
- private int _integer;
+ private EventTracker<String> tracker;
+ private double random;
+ private int integer;
public Environment() {
this("environment");
public Environment(String aName, String aPrefix) {
super(aName, provided(aPrefix), new RequiredInterface[0]);
- _random = Math.random();
- _integer = COUNT++;
+ random = Math.random();
+ integer = COUNT++;
}
public Environment(EventTracker aTracker) {
this();
- _tracker = aTracker;
+ tracker = aTracker;
}
public Integer getInteger() {
- return _integer;
+ return integer;
}
public String getString() {
addInterface(getProvidedInterfaces().get(0), getString(), aScope);
addInterface(getProvidedInterfaces().get(1), getInteger(), aScope);
track("start." + getName());
- return _random;
+ return random;
}
@Override
protected void doStop(Object aRuntime) {
track("stop." + getName());
- if (_random != (Double) aRuntime) {
+ if (random != (Double) aRuntime) {
throw new IllegalArgumentException("Wrong runtime: expected "
- + _random + " but got " + aRuntime);
+ + random + " but got " + aRuntime);
}
}
private void track(String aString) {
- if (_tracker == null) {
+ if (tracker == null) {
return;
}
- _tracker.eventOccurred(aString);
+ tracker.eventOccurred(aString);
}
}
new DefaultProvidedInterface(aPrefix + "integer", Integer.class) };
}
- private EventTracker<String> _tracker;
- private double _random;
+ private EventTracker<String> tracker;
+ private double random;
public IntegerComponent() {
this("environment");
public IntegerComponent(String aName, String aPrefix) {
super(aName, provided(aPrefix), new RequiredInterface[0]);
- _random = Math.random();
+ random = Math.random();
}
public IntegerComponent(EventTracker aTracker) {
this();
- _tracker = aTracker;
+ tracker = aTracker;
}
public Integer getInteger() {
protected Object doStart(Scope aScope) {
addInterface(getProvidedInterfaces().get(1), getInteger(), aScope);
track("start." + getName());
- return _random;
+ return random;
}
@Override
protected void doStop(Object aRuntime) {
track("stop." + getName());
- if (_random != (Double) aRuntime) {
+ if (random != (Double) aRuntime) {
throw new IllegalArgumentException("Wrong runtime: expected "
- + _random + " but got " + aRuntime);
+ + random + " but got " + aRuntime);
}
}
private void track(String aString) {
- if (_tracker == null) {
+ if (tracker == null) {
return;
}
- _tracker.eventOccurred(aString);
+ tracker.eventOccurred(aString);
}
}
new DefaultProvidedInterface(aPrefix + "datasource", String.class) };
}
- private EventTracker<String> _tracker;
- private double _random;
+ private EventTracker<String> tracker;
+ private double random;
public StringComponent() {
this("environment");
public StringComponent(String aName, String aPrefix) {
super(aName, provided(aPrefix), new RequiredInterface[0]);
- _random = Math.random();
+ random = Math.random();
}
public StringComponent(EventTracker aTracker) {
this();
- _tracker = aTracker;
+ tracker = aTracker;
}
public Integer getInteger() {
protected Object doStart(Scope aScope) {
addInterface(getProvidedInterfaces().get(0), getString(), aScope);
track("start." + getName());
- return _random;
+ return random;
}
@Override
protected void doStop(Object aRuntime) {
track("stop." + getName());
- if (_random != (Double) aRuntime) {
+ if (random != (Double) aRuntime) {
throw new IllegalArgumentException("Wrong runtime: expected "
- + _random + " but got " + aRuntime);
+ + random + " but got " + aRuntime);
}
}
private void track(String aString) {
- if (_tracker == null) {
+ if (tracker == null) {
return;
}
- _tracker.eventOccurred(aString);
+ tracker.eventOccurred(aString);
}
}
import org.wamblee.system.graph.component.RequiredInterfaceNode;
public class CompositeEdgeFilterTest extends TestCase {
- private Application _app = new Application();
- private Environment _env = new Environment();
+ private Application app = new Application();
+ private Environment env = new Environment();
private Edge createEdge(Component aClient, RequiredInterface aRequired,
Component aServer, ProvidedInterface aProvided) {
public void testEmpty() {
EdgeFilter restriction = new CompositeEdgeFilter();
- assertFalse(restriction.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0),
- _env, _env.getProvidedInterfaces().get(0))));
+ assertFalse(restriction.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
+ env, env.getProvidedInterfaces().get(0))));
}
private void configureRestriction(EdgeFilter base, boolean aResult) {
configureRestriction(base, false);
- assertFalse(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0),
- _env, _env.getProvidedInterfaces().get(0))));
+ assertFalse(composite.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
+ env, env.getProvidedInterfaces().get(0))));
// Second let the base return true and verify the result.
configureRestriction(base, true);
- assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0),
- _env, _env.getProvidedInterfaces().get(0))));
+ assertTrue(composite.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
+ env, env.getProvidedInterfaces().get(0))));
}
configureRestriction(base1, false);
configureRestriction(base2, false);
- assertFalse(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0),
- _env, _env.getProvidedInterfaces().get(0))));
+ assertFalse(composite.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
+ env, env.getProvidedInterfaces().get(0))));
// 2. base 1 not violated but base 2 violated -> violated
configureRestriction(base1, false);
configureRestriction(base2, true);
- assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0),
- _env, _env.getProvidedInterfaces().get(0))));
+ assertTrue(composite.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
+ env, env.getProvidedInterfaces().get(0))));
// 3. base 1 violated -> violated and base 2 not called.
configureRestriction(base1, true);
// base 2 should not be called.
- assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0),
- _env, _env.getProvidedInterfaces().get(0))));
+ assertTrue(composite.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
+ env, env.getProvidedInterfaces().get(0))));
}
}
public class MyNode extends DefaultNode {
- private String[] _ports;
+ private String[] ports;
public MyNode(String aName, String[] aPorts) {
super(aName);
- _ports = aPorts;
+ ports = aPorts;
}
public String[] getPorts() {
- return _ports;
+ return ports;
}
}
public class ConnectExternalProvidedProvidedEdgeFilterTest extends TestCase {
- private Container _container;
- private Component<Object> _internal;
- private String _externalInterfaceName;
- private String _internalComponentName;
- private String _internalInterfaceName;
- private Edge _edge;
+ private Container container;
+ private Component<Object> internal;
+ private String externalInterfaceName;
+ private String internalComponentName;
+ private String internalInterfaceName;
+ private Edge edge;
@Override
protected void setUp() throws Exception {
- _container = new Container("container")
+ container = new Container("container")
.addProvidedInterface(new DefaultProvidedInterface("string",
String.class));
- _internal = new Environment("env1");
+ internal = new Environment("env1");
- _externalInterfaceName = _container.getProvidedInterfaces().get(0)
+ externalInterfaceName = container.getProvidedInterfaces().get(0)
.getName();
- _internalComponentName = _internal.getName();
- _internalInterfaceName = _internal.getProvidedInterfaces().get(0).getName();
+ internalComponentName = internal.getName();
+ internalInterfaceName = internal.getProvidedInterfaces().get(0).getName();
- _edge = new DefaultEdge(new ExternalProvidedInterfaceNode(_container,
- _container.getProvidedInterfaces().get(0)),
- new ProvidedInterfaceNode(_internal, _internal
+ edge = new DefaultEdge(new ExternalProvidedInterfaceNode(container,
+ container.getProvidedInterfaces().get(0)),
+ new ProvidedInterfaceNode(internal, internal
.getProvidedInterfaces().get(0)));
}
public void testWrongExternal() {
EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
- _externalInterfaceName + "x", _internalComponentName,
- _internalInterfaceName);
- assertFalse(filter.isViolated(_edge));
+ externalInterfaceName + "x", internalComponentName,
+ internalInterfaceName);
+ assertFalse(filter.isViolated(edge));
}
public void testRightExternalWrongComponent() {
EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
- _externalInterfaceName, _internalComponentName + "x",
- _internalInterfaceName);
- assertTrue(filter.isViolated(_edge));
+ externalInterfaceName, internalComponentName + "x",
+ internalInterfaceName);
+ assertTrue(filter.isViolated(edge));
}
public void testRightExternalWrongInternal() {
EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
- _externalInterfaceName, _internalComponentName,
- _internalInterfaceName + "x");
- assertTrue(filter.isViolated(_edge));
+ externalInterfaceName, internalComponentName,
+ internalInterfaceName + "x");
+ assertTrue(filter.isViolated(edge));
}
public void testEverythingRight() {
EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
- _externalInterfaceName, _internalComponentName,
- _internalInterfaceName);
- assertFalse(filter.isViolated(_edge));
+ externalInterfaceName, internalComponentName,
+ internalInterfaceName);
+ assertFalse(filter.isViolated(edge));
}
public void testWrongEdgeType() {
EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
- _externalInterfaceName, _internalComponentName,
- _internalInterfaceName);
+ externalInterfaceName, internalComponentName,
+ internalInterfaceName);
DefaultEdge edge = new DefaultEdge(new DefaultNode("x"),
new DefaultNode("y"));
assertFalse(filter.isViolated(edge));
public class ConnectRequiredExternallyRequiredEdgeFilterTest extends TestCase {
- private Component<?> _comp;
- private Container _container;
- private Edge _edge;
+ private Component<?> comp;
+ private Container container;
+ private Edge edge;
@Override
protected void setUp() throws Exception {
- _comp = new Application();
- _container = new Container("container")
+ comp = new Application();
+ container = new Container("container")
.addRequiredInterface(new DefaultRequiredInterface("x",
String.class));
- Node req = new RequiredInterfaceNode(_comp, _comp
+ Node req = new RequiredInterfaceNode(comp, comp
.getRequiredInterfaces().get(0));
- Node external = new ExternalRequiredInterfaceNode(_container,
- _container.getRequiredInterfaces().get(0));
- _edge = new DefaultEdge(req, external);
+ Node external = new ExternalRequiredInterfaceNode(container,
+ container.getRequiredInterfaces().get(0));
+ edge = new DefaultEdge(req, external);
}
public void testRightComponentRightInterface() {
EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
- _comp.getName(), _comp.getRequiredInterfaces().get(0).getName(),
- _container.getRequiredInterfaces().get(0).getName());
- assertFalse(filter.isViolated(_edge));
+ comp.getName(), comp.getRequiredInterfaces().get(0).getName(),
+ container.getRequiredInterfaces().get(0).getName());
+ assertFalse(filter.isViolated(edge));
}
public void testWrongInterface() {
EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
- _comp.getName(), _comp.getRequiredInterfaces().get(0).getName()
- + "xx", _container.getRequiredInterfaces().get(0).getName());
- assertFalse(filter.isViolated(_edge));
+ comp.getName(), comp.getRequiredInterfaces().get(0).getName()
+ + "xx", container.getRequiredInterfaces().get(0).getName());
+ assertFalse(filter.isViolated(edge));
}
public void testWrongComponent() {
EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
- _comp.getName() + "xx", _comp.getRequiredInterfaces().get(0)
- .getName(), _container.getRequiredInterfaces().get(0)
+ comp.getName() + "xx", comp.getRequiredInterfaces().get(0)
+ .getName(), container.getRequiredInterfaces().get(0)
.getName());
- assertFalse(filter.isViolated(_edge));
+ assertFalse(filter.isViolated(edge));
}
public void testWrongExternalInterface() {
EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
- _comp.getName(), _comp.getRequiredInterfaces().get(0).getName(),
- _container.getRequiredInterfaces().get(0).getName() + "xx");
- assertTrue(filter.isViolated(_edge));
+ comp.getName(), comp.getRequiredInterfaces().get(0).getName(),
+ container.getRequiredInterfaces().get(0).getName() + "xx");
+ assertTrue(filter.isViolated(edge));
}
public void testWrongEdgeType() {
DefaultEdge edge = new DefaultEdge(new DefaultNode("x"),
new DefaultNode("y"));
EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
- _comp.getName(), _comp.getRequiredInterfaces().get(0).getName(),
- _container.getRequiredInterfaces().get(0).getName());
+ comp.getName(), comp.getRequiredInterfaces().get(0).getName(),
+ container.getRequiredInterfaces().get(0).getName());
assertFalse(filter.isViolated(edge));
}
}
public class ConnectRequiredProvidedEdgeFilterTest extends TestCase {
- private Application _app1 = new Application("app1", "pf1.");
- private Application _app2 = new Application("app2", "pf2.");
+ private Application app1 = new Application("app1", "pf1.");
+ private Application app2 = new Application("app2", "pf2.");
- private Environment _env1 = new Environment("env1", "pf3.");
- private Environment _env2 = new Environment("env2", "pf4.");
+ private Environment env1 = new Environment("env1", "pf3.");
+ private Environment env2 = new Environment("env2", "pf4.");
private void compare(Boolean[] aExpected, EdgeFilter aRestriction) {
// env1, app2
// env2, app1
// env2, app2
- for (Environment env: new Environment[] { _env1, _env2} ) {
- for (Application app: new Application[] { _app1, _app2} ) {
+ for (Environment env: new Environment[] { env1, env2} ) {
+ for (Application app: new Application[] { app1, app2} ) {
Node from = new RequiredInterfaceNode(
app, app.getRequiredInterfaces().get(0));
Node to = new ProvidedInterfaceNode(
}
public void testExplicitConfig() {
- _app1 = new Application("app1");
- _app2 = new Application("app2");
- _env1 = new Environment("env1");
- _env2 = new Environment("env2");
+ app1 = new Application("app1");
+ app2 = new Application("app2");
+ env1 = new Environment("env1");
+ env2 = new Environment("env2");
EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(
"app2", "string", "env1", "datasource");
static final ThreadLocal<SpringComponent> THIS = new ThreadLocal<SpringComponent>();
static final ThreadLocal<Scope> SCOPE = new ThreadLocal<Scope>();
- private Properties _properties;
- private String[] _configFiles;
- private Map<String, ProvidedInterface> _provided;
- private Map<RequiredInterface, String> _required;
- private Map<String, Properties> _propertyObjects;
+ private Properties properties;
+ private String[] configFiles;
+ private Map<String, ProvidedInterface> provided;
+ private Map<RequiredInterface, String> required;
+ private Map<String, Properties> propertyObjects;
/**
* Constructs a spring system.
Map<RequiredInterface, String> aRequired) {
super(aName, aProvided.values().toArray(new ProvidedInterface[0]),
aRequired.keySet().toArray(new RequiredInterface[0]));
- _properties = new Properties();
- _configFiles = aConfigFiles;
- _provided = aProvided;
- _required = aRequired;
- _propertyObjects = new HashMap<String, Properties>();
+ properties = new Properties();
+ configFiles = aConfigFiles;
+ provided = aProvided;
+ required = aRequired;
+ propertyObjects = new HashMap<String, Properties>();
}
* Property value.
*/
public void setProperty(String aKey, String aValue) {
- _properties.put(aKey, aValue);
+ properties.put(aKey, aValue);
}
public void addProperties(Properties aProperties) {
}
public void addProperties(String aBeanname, Properties aProperties) {
- _propertyObjects.put(aBeanname, aProperties);
+ propertyObjects.put(aBeanname, aProperties);
}
public Properties getProperties(String aBeanname) {
- return _propertyObjects.get(aBeanname);
+ return propertyObjects.get(aBeanname);
}
@Override
AbstractApplicationContext context = parseConfigFiles(parentContext);
context
- .addBeanFactoryPostProcessor(new PropertySetter(_properties));
+ .addBeanFactoryPostProcessor(new PropertySetter(properties));
context.refresh();
exposeProvidedServices(context, aExternalScope);
private void exposeProvidedServices(AbstractApplicationContext aContext, Scope aScope) {
// Call addService for each provided service.
- for (String name : _provided.keySet()) {
+ for (String name : provided.keySet()) {
Object svc = aContext.getBean(name);
if (svc == null) {
throw new IllegalArgumentException(getQualifiedName() + ": service '"
+ name + "' is null");
}
- addInterface(_provided.get(name), svc, aScope);
- System.out.println("addService " + _provided.get(name) + " " + svc);
+ addInterface(provided.get(name), svc, aScope);
+ System.out.println("addService " + provided.get(name) + " " + svc);
}
}
private AbstractApplicationContext parseConfigFiles(GenericApplicationContext aParentContext) {
// Parse spring config files
- return new ClassPathXmlApplicationContext((String[]) _configFiles,
+ return new ClassPathXmlApplicationContext((String[]) configFiles,
false, aParentContext);
}
private void registerRequiredServices(GenericApplicationContext aParentContext) {
// Register required services in a parent context
- for (RequiredInterface required: getRequiredInterfaces()) {
- String beanName = _required.get(required);
+ for (RequiredInterface requiredIntf: getRequiredInterfaces()) {
+ String beanName = required.get(requiredIntf);
if ( beanName != null && beanName.length() > 0) {
ConstructorArgumentValues cargs = new ConstructorArgumentValues();
- cargs.addGenericArgumentValue(required.getName());
+ cargs.addGenericArgumentValue(requiredIntf.getName());
BeanDefinition definition = new RootBeanDefinition(
RequiredServiceBean.class, cargs,
new MutablePropertyValues());
}
private void registerPropertyObjects(GenericApplicationContext aParentContext) {
- for (String beanName: _propertyObjects.keySet()) {
+ for (String beanName: propertyObjects.keySet()) {
ConstructorArgumentValues cargs = new ConstructorArgumentValues();
- cargs.addGenericArgumentValue(PropertySetter.createPropertyFile(_propertyObjects.get(beanName)));
+ cargs.addGenericArgumentValue(PropertySetter.createPropertyFile(propertyObjects.get(beanName)));
BeanDefinition definition = new RootBeanDefinition(
ConfiguredProperties.class, cargs,
new MutablePropertyValues());
package org.wamblee.system.spring;
public class BlaService {
- private HelloService _hello;
+ private HelloService hello;
public BlaService(HelloService aService) {
if ( aService == null ) {
throw new IllegalArgumentException("helloService is null");
}
- _hello = aService;
+ hello = aService;
}
public String execute() {
- return _hello.say();
+ return hello.say();
}
public void stop() {
public class HelloService {
- private String _msg;
+ private String msg;
public HelloService(String aMsg) {
SpringComponentTest.EVENT_TRACKER.eventOccurred(aMsg);
- _msg = aMsg;
+ msg = aMsg;
}
public String say() {
- return _msg;
+ return msg;
}
}
public class HelloService2 {
- private Properties _props;
+ private Properties props;
public HelloService2(Properties aProps) {
- _props = aProps;
+ props = aProps;
}
public Properties getProperties() {
- return _props;
+ return props;
}
}
public static EventTracker<String> EVENT_TRACKER;
- private Scope _externalScope;
+ private Scope externalScope;
@Override
protected void setUp() throws Exception {
super.setUp();
EVENT_TRACKER = new EventTracker<String>();
- _externalScope = new DefaultScope(new ProvidedInterface[0]);
+ externalScope = new DefaultScope(new ProvidedInterface[0]);
}
public void testBlackboxSystem() {
new HashMap<String, ProvidedInterface>(),
new HashMap<RequiredInterface, String>());
- Scope runtime = system.start(_externalScope);
- assertEquals(0, _externalScope.getProvidedInterfaces().size());
+ Scope runtime = system.start(externalScope);
+ assertEquals(0, externalScope.getProvidedInterfaces().size());
system.stop(runtime);
}
SpringComponent system = new SpringComponent("system",
new String[] { HELLO_SERVICE_SPRING_XML }, provided,
new HashMap<RequiredInterface, String>());
- Scope runtime = system.start(_externalScope);
+ Scope runtime = system.start(externalScope);
List<ProvidedInterface> services = runtime.getProvidedInterfaces();
assertEquals(1, services.size());
// BUG; Provided services should be made available in the external
// scope.
- Object service2 = _externalScope.getInterfaceImplementation(provided
+ Object service2 = externalScope.getInterfaceImplementation(provided
.get("helloService"), Object.class);
assertSame(service, service2);
props.load(new ClassPathResource(PROPERTY_FILE).getInputStream());
system.addProperties(props);
- Scope scope = system.start(_externalScope);
+ Scope scope = system.start(externalScope);
// BUG: Hello service was constructed multiple times. Once with the
// unprocessed property
// and another time with the processed property.
props.load(new ClassPathResource(PROPERTY_FILE).getInputStream());
system.addProperties("properties", props);
- Scope scope = system.start(_externalScope);
+ Scope scope = system.start(externalScope);
List<ProvidedInterface> services = scope.getProvidedInterfaces();
new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
new HashMap<String, ProvidedInterface>(),
new HashMap<RequiredInterface, String>());
- system.start(_externalScope);
+ system.start(externalScope);
} catch (SystemAssemblyException e) {
// e.printStackTrace();
return;
new String[] { HELLO_SERVICE_SPRING_XML }, provided,
new HashMap<RequiredInterface, String>());
- Scope runtime = system.start(_externalScope);
+ Scope runtime = system.start(externalScope);
List<ProvidedInterface> services = runtime.getProvidedInterfaces();
assertEquals(2, services.size());
// BUG; Provided services should be made available in the external
// scope.
- Object service2 = _externalScope.getInterfaceImplementation(provided
+ Object service2 = externalScope.getInterfaceImplementation(provided
.get("helloService"), Object.class);
assertSame(service, service2);
- Object floatsvc = _externalScope.getInterfaceImplementation(system
+ Object floatsvc = externalScope.getInterfaceImplementation(system
.getProvidedInterfaces().get(1), Object.class);
assertTrue(floatsvc instanceof Float);
assertTrue((((Float) floatsvc).floatValue() - 100.345f) < 0.00001);
/**
* Cached spring application context.
*/
- private ApplicationContext _context;
+ private ApplicationContext context;
- private HibernateTemplate _hibernateTemplate;
+ private HibernateTemplate hibernateTemplate;
- private PlatformTransactionManager _transactionManager;
+ private PlatformTransactionManager transactionManager;
- private DataSource _dataSource;
+ private DataSource dataSource;
public DatabaseTesterComponent(HibernateTemplate aHibernateTemplate,
PlatformTransactionManager aTransactionManager,
DataSource aDataSource) {
- _hibernateTemplate = aHibernateTemplate;
- _transactionManager = aTransactionManager;
- _dataSource = aDataSource;
+ hibernateTemplate = aHibernateTemplate;
+ transactionManager = aTransactionManager;
+ dataSource = aDataSource;
}
/**
* @return Hibernate session factory.
*/
protected SessionFactory getSessionFactory() {
- return _hibernateTemplate.getSessionFactory();
+ return hibernateTemplate.getSessionFactory();
}
/**
* @return Transaction manager
*/
protected PlatformTransactionManager getTransactionManager() {
- return _transactionManager;
+ return transactionManager;
}
/**
* @return Hibernate template.
*/
public HibernateTemplate getTemplate() {
- return _hibernateTemplate;
+ return hibernateTemplate;
}
/**
* @return Returns the dataSource.
*/
public DataSource getDataSource() {
- return _dataSource;
+ return dataSource;
}
/**
public class CompositeJpaCustomizer implements JpaCustomizer {
- private List<JpaCustomizer> _customizers;
- private CompositeJpaTables _tables;
+ private List<JpaCustomizer> customizers;
+ private CompositeJpaTables tables;
public CompositeJpaCustomizer(List<JpaCustomizer> aCustomizers) {
- _customizers = aCustomizers;
- _tables = new CompositeJpaTables();
- for (JpaCustomizer customizer: _customizers) {
- _tables.add(customizer.getJpaTables());
+ customizers = aCustomizers;
+ tables = new CompositeJpaTables();
+ for (JpaCustomizer customizer: customizers) {
+ tables.add(customizer.getJpaTables());
}
}
@Override
public void customize(PersistenceUnitDescription aPersistenceUnit, Map<String, String> aJpaProperties) {
- for (JpaCustomizer customizer: _customizers) {
+ for (JpaCustomizer customizer: customizers) {
customizer.customize(aPersistenceUnit, aJpaProperties);
}
}
@Override
public ITableFilterSimple getJpaTables() {
- return _tables;
+ return tables;
}
}
public class CompositeJpaTables implements ITableFilterSimple {
- private List<ITableFilterSimple> _tables;
+ private List<ITableFilterSimple> tables;
public CompositeJpaTables() {
- _tables = new ArrayList<ITableFilterSimple>();
+ tables = new ArrayList<ITableFilterSimple>();
}
public void add(ITableFilterSimple aFilter) {
- _tables.add(aFilter);
+ tables.add(aFilter);
}
@Override
public boolean accept(String aTableName) throws DataSetException {
- for (ITableFilterSimple filter: _tables) {
+ for (ITableFilterSimple filter: tables) {
if (filter.accept(aTableName)) {
return true;
}
/**
* Database class which encapsulates management of the database.
*/
- private Class _databaseClass;
+ private Class databaseClass;
/**
* Execution as a main program. Commandline
+ aClass.getName( )
+ "' is not a subclass of Database" );
}
- _databaseClass = aClass;
+ databaseClass = aClass;
}
/**
* @throws Exception
*/
public void start( ) throws Exception {
- Database lDatabase = (Database) _databaseClass.newInstance( );
+ Database lDatabase = (Database) databaseClass.newInstance( );
lDatabase.start( );
System.out.println( "Database has been started. " );
System.out.println( );