formatting.
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.wamblee</groupId>
<artifactId>wamblee-utils</artifactId>
</developer>
</developers>
- <modules>
+ <modules>
<module>support</module>
<module>system</module>
<module>hibernate-jpa</module>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
-
+
</dependencies>
</dependencyManagement>
</dependency>
</dependencies>
</plugin>
-
+
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.4</version>
<dependency>
<groupId>org.wamblee</groupId>
<artifactId>wamblee-code-style</artifactId>
- <version>1.0</version>
+ <version>1.1-SNAPSHOT</version>
</dependency>
</dependencies>
</plugin>
</reportSet>
</reportSets>
</plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ <version>2.3.1</version>
+ <configuration>
+ <xmlOutput>true</xmlOutput>
+ <!-- Optional derectory to put findbugs xdoc xml report -->
+ <xmlOutputDirectory>target/site</xmlOutputDirectory>
+ <findbugsXmlOutput>true</findbugsXmlOutput>
+ <!-- Optional directory to put findbugs xml report -->
+ <findbugsXmlOutputDirectory>target/site</findbugsXmlOutputDirectory>
+ </configuration>
+
+ </plugin>
+
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>changes-maven-plugin</artifactId>
<url>http://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
-
+
</profile>
<profile>
<id>all</id>
* An superclass of all other operations.
*/
public class AllOperation implements Operation {
- /**
- * DOCUMENT ME!
- */
private static final String OPERATION = "all";
/**
*/
private String name;
-/**
- * Constructs an all operation.
- *
+ /**
+ * Constructs an all operation.
+ *
*/
public AllOperation() {
name = OPERATION;
}
-/**
+ /**
* Constructs the operation, this constructor is the one that must be used
- * by subclasses.
- * @param aName Name of the operation. This name must be unique among all operations.
+ * by subclasses.
+ *
+ * @param aName
+ * Name of the operation. This name must be unique among all
+ * operations.
*/
protected AllOperation(String aName) {
name = aName;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.security.authorization.Operation#getName()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String getName() {
return name;
}
import org.wamblee.usermgt.User;
-
/**
* Matches any user.
- *
+ *
* @author Erik Brakkee
*/
-public class AnyUserCondition extends AbstractPersistent
- implements UserCondition {
-/**
- * Constructs the condition.
- *
+public class AnyUserCondition extends AbstractPersistent implements
+ UserCondition {
+ /**
+ * Constructs the condition.
+ *
*/
public AnyUserCondition() {
- // Empty.
+ // Empty.
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.UserCondition#matches(org.wamblee.usermgt.User)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.UserCondition#matches(org.wamblee.
+ * usermgt.User)
*/
public boolean matches(User aUser) {
return true;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#toString()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return "AnyUserCondition()";
/**
* Authorization exception to be thrown when a resouce may not be accessed.
- *
+ *
* @author Erik Brakkee
*/
public class AuthorizationException extends RuntimeException {
- /**
- * DOCUMENT ME!
- */
private Object resource;
- /**
- * DOCUMENT ME!
- */
private Operation operation;
-/**
+ /**
* Creates a new AuthorizationException object.
- *
- * @param aResource DOCUMENT ME!
- * @param aOperation DOCUMENT ME!
+ *
*/
public AuthorizationException(Object aResource, Operation aOperation) {
- super("Operation '" + aOperation + "' not allowed on '" + aResource
- + "'");
- resource = aResource;
- operation = aOperation;
+ super("Operation '" + aOperation + "' not allowed on '" + aResource +
+ "'");
+ resource = aResource;
+ operation = aOperation;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Object getResource() {
return resource;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Operation getOperation() {
return operation;
}
import org.apache.log4j.Logger;
-
/**
* Inititializer class for authorization rules. This class initializes the
* authorization rules in case none are present.
*/
public class AuthorizationInitializer {
- /**
- * DOCUMENT ME!
- */
- private static final Logger LOGGER = Logger.getLogger(AuthorizationInitializer.class);
+ private static final Logger LOGGER = Logger
+ .getLogger(AuthorizationInitializer.class);
-/**
- * Initializes authorization rules in case none are present.
- * @param aService Authorization service.
- * @param aRules Default rules for initialization.
+ /**
+ * Initializes authorization rules in case none are present.
+ *
+ * @param aService
+ * Authorization service.
+ * @param aRules
+ * Default rules for initialization.
*/
public AuthorizationInitializer(AuthorizationService aService,
AuthorizationRule[] aRules) {
/**
* Represents the result of an authorization decision.
- *
+ *
* @author Erik Brakkee
*/
public enum AuthorizationResult {
-/**
+ /**
* Access is granted.
*/
GRANTED,
-/**
+ /**
* Access is denied.
*/
DENIED,
-/**
+ /**
* Access is undecided.
*/
UNDECIDED,
-/**
+ /**
* Unsupported resource.
*/
UNSUPPORTED_RESOURCE;
import org.wamblee.usermgt.User;
-
/**
- * Represents an authorization rule to determine whether an operation is allowed on a resource.
- *
+ * Represents an authorization rule to determine whether an operation is allowed
+ * on a resource.
+ *
* @author Erik Brakkee
*/
public interface AuthorizationRule extends Persistent {
/**
- * Returns the supported object types for which this authorization
- * rule applies. This can be used by the authorization service for
- * optimization.
- *
+ * Returns the supported object types for which this authorization rule
+ * applies. This can be used by the authorization service for optimization.
+ *
* @return Array of supported types.
*/
Class[] getSupportedTypes();
/**
- * Determines whether an operation is allowed on a certain
- * resource. The rule implementation must be prepared to deal with
- * resources for which it does not apply. In those cases it should return
+ * Determines whether an operation is allowed on a certain resource. The
+ * rule implementation must be prepared to deal with resources for which it
+ * does not apply. In those cases it should return
* {@link AuthorizationResult#UNSUPPORTED_RESOURCE}.
- *
- * @param aResource Resource.
- * @param anOperation Operation.
- * @param aUser Current user.
- *
+ *
+ * @param aResource
+ * Resource.
+ * @param anOperation
+ * Operation.
+ * @param aUser
+ * Current user.
+ *
* @return Authorization result.
*/
AuthorizationResult isAllowed(Object aResource, Operation anOperation,
import org.wamblee.persistence.Persistent;
-
/**
- * Service to determine if access to a certain resource is allowed.
- *
+ * Service to determine if access to a certain resource is allowed.
+ *
* @author Erik Brakkee
*/
public interface AuthorizationService extends Persistent {
/**
* Checks whether an operation is allowed on a resource.
- *
- * @param aResource Resource.
- * @param aOperation Operation.
- *
+ *
+ * @param aResource
+ * Resource.
+ * @param aOperation
+ * Operation.
+ *
* @return Checks whether the operation is allowed on a resource.
*/
boolean isAllowed(Object aResource, Operation aOperation);
- /**
- * DOCUMENT ME!
- *
- * @param <T> DOCUMENT ME!
- * @param aResource DOCUMENT ME!
- * @param aOperation DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
<T> T check(T aResource, Operation aOperation);
/**
* Gets the authorization rules.
- *
+ *
* @return Rules.
*/
AuthorizationRule[] getRules();
/**
* Appends a new authorization rule to the end.
- *
- * @param aRule Rule to append.
+ *
+ * @param aRule
+ * Rule to append.
*/
void appendRule(AuthorizationRule aRule);
/**
* Removes a rule.
- *
- * @param aIndex Index of the rule to remove.
+ *
+ * @param aIndex
+ * Index of the rule to remove.
*/
void removeRule(int aIndex);
/**
* Inserts a rule.
- *
- * @param aIndex Index of the position of the rule after insertion.
- * @param aRule Rule to insert.
+ *
+ * @param aIndex
+ * Index of the position of the rule after insertion.
+ * @param aRule
+ * Rule to insert.
*/
void insertRuleAfter(int aIndex, AuthorizationRule aRule);
}
/**
* Represents an operation to create something.
- *
+ *
* @author Erik Brakkee
*/
public class CreateOperation extends AllOperation {
- /**
- * DOCUMENT ME!
- */
private static final String OPERATION = "create";
-/**
- * Constructs the operation.
- *
+ /**
+ * Constructs the operation.
+ *
*/
public CreateOperation() {
super(OPERATION);
import java.util.ArrayList;
import java.util.List;
-
/**
- * Default implementation of an authorization service. To determine
- * whether access to a resource is allowed, the service consults a number of
+ * Default implementation of an authorization service. To determine whether
+ * access to a resource is allowed, the service consults a number of
* authorization rules in a fixed order. The first rule that gives a result
- * GRANTED or DENIED determines the result of the evaluation. Rules that
- * return any other result are ignoed. If none of the rules match, than
- * access is denied.
- *
+ * GRANTED or DENIED determines the result of the evaluation. Rules that return
+ * any other result are ignoed. If none of the rules match, than access is
+ * denied.
+ *
* @author Erik Brakkee
*/
-public class DefaultAuthorizationService extends AbstractPersistent
- implements AuthorizationService {
+public class DefaultAuthorizationService extends AbstractPersistent implements
+ AuthorizationService {
/**
* List of ordered authorization rules.
*/
*/
private String name;
-/**
- * Constructs the service.
- * @param aAccessor User accessor.
- * @param aName Name of this instance of the service.
+ /**
+ * Constructs the service.
+ *
+ * @param aAccessor
+ * User accessor.
+ * @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.
+ /**
+ * Constructs the authorization service.
*/
public DefaultAuthorizationService() {
- rules = new ArrayList<AuthorizationRule>();
- userAccessor = null;
- name = null;
+ rules = new ArrayList<AuthorizationRule>();
+ userAccessor = null;
+ name = null;
}
/**
* Sets the user accessor.
- *
- * @param aUserAccessor User accessor.
+ *
+ * @param aUserAccessor
+ * User accessor.
*/
public void setUserAccessor(UserAccessor aUserAccessor) {
userAccessor = aUserAccessor;
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aResource DOCUMENT ME!
- * @param aOperation DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ /*
+ * (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) {
switch (rule.isAllowed(aResource, aOperation, user)) {
- case DENIED:
- return false;
+ case DENIED:
+ return false;
- case GRANTED:
- return true;
+ case GRANTED:
+ return true;
}
}
return false;
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.AuthorizationService#check(T, org.wamblee.security.authorization.Operation)
- */
- /**
- * DOCUMENT ME!
- *
- * @param <T> DOCUMENT ME!
- * @param aResource DOCUMENT ME!
- * @param aOperation DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws AuthorizationException DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.wamblee.security.authorization.AuthorizationService#check(T,
+ * org.wamblee.security.authorization.Operation)
*/
public <T> T check(T aResource, Operation aOperation) {
if (!isAllowed(aResource, aOperation)) {
return aResource;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
protected String getName() {
return name;
}
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- */
public void setName(String aName) {
name = aName;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.security.authorization.AuthorizationService#getRules()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public AuthorizationRule[] getRules() {
return rules.toArray(new AuthorizationRule[0]);
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aRule DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.AuthorizationService#appendRule(org
+ * .wamblee.security.authorization.AuthorizationRule)
*/
public void appendRule(AuthorizationRule aRule) {
rules.add(aRule);
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int, org.wamblee.security.authorization.AuthorizationRule)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aIndex DOCUMENT ME!
- * @param aRule DOCUMENT ME!
+ /*
+ * (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);
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.AuthorizationService#removeRule(int)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aIndex DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.AuthorizationService#removeRule(int)
*/
public void removeRule(int aIndex) {
rules.remove(aIndex);
/**
* For OR mapping.
- *
+ *
* @return The rules.
*/
protected List<AuthorizationRule> getMappedRules() {
/**
* For OR mapping.
- *
- * @param aRules The rules.
+ *
+ * @param aRules
+ * The rules.
*/
protected void setMappedRules(List<AuthorizationRule> aRules) {
rules = aRules;
import java.util.Map;
import java.util.TreeMap;
-
/**
- * Operation registry implementation. This implementation ignores the
+ * Operation registry implementation. This implementation ignores the
* distinction between different types of resources and simply assumes that
* every operation is applicable to every type of resource.
- *
+ *
* @author Erik Brakkee
*/
public class DefaultOperationRegistry implements OperationRegistry {
- /**
- * DOCUMENT ME!
- */
private Map<String, Operation> operations;
-/**
+ /**
* Creates a new DefaultOperationRegistry object.
- *
- * @param aOperations DOCUMENT ME!
+ *
*/
public DefaultOperationRegistry(Operation[] aOperations) {
operations = new TreeMap<String, Operation>();
}
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.OperationRegistry#getOperations(java.lang.Class)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aResourceClass DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.OperationRegistry#getOperations(java
+ * .lang.Class)
*/
public Operation[] getOperations(Class aResourceClass) {
return operations.values().toArray(new Operation[0]);
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.OperationRegistry#encode(org.wamblee.security.authorization.Operation[])
- */
- /**
- * DOCUMENT ME!
- *
- * @param aOperations DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.OperationRegistry#encode(org.wamblee
+ * .security.authorization.Operation[])
*/
public String encode(Operation[] aOperations) {
StringBuffer buffer = new StringBuffer();
return buffer.toString();
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.OperationRegistry#decode(java.lang.Class, java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aResourceClass DOCUMENT ME!
- * @param aOperationsString DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.OperationRegistry#decode(java.lang
+ * .Class, java.lang.String)
*/
public Operation[] decode(Class aResourceClass, String aOperationsString) {
return decode(aOperationsString);
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.OperationRegistry#decode(java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aOperationsString DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IllegalArgumentException DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.OperationRegistry#decode(java.lang
+ * .String)
*/
public Operation[] decode(String aOperationsString) {
if (aOperationsString.length() == 0) {
return new Operation[0];
}
- String[] names = aOperationsString.split(",");
+ String[] names = aOperationsString.split(",");
ArrayList<Operation> result = new ArrayList<Operation>();
for (String name : names) {
Operation operation = operations.get(name);
if (operation == null) {
- throw new IllegalArgumentException("Unknown operation '" + name
- + "'");
+ throw new IllegalArgumentException("Unknown operation '" +
+ name + "'");
}
result.add(operation);
/**
* Deletes the operation.
- *
+ *
* @author Erik Brakkee
*/
public class DeleteOperation extends AllOperation {
- /**
- * DOCUMENT ME!
- */
private static final String OPERATION = "delete";
-/**
- * Constructs the operation.
- *
+ /**
+ * Constructs the operation.
+ *
*/
public DeleteOperation() {
super(OPERATION);
import org.wamblee.usermgt.User;
-
/**
* Checks if a user against a specific group.
- *
+ *
* @author Erik Brakkee
*/
-public class GroupUserCondition extends AbstractPersistent
- implements UserCondition {
+public class GroupUserCondition extends AbstractPersistent implements
+ UserCondition {
/**
* Group the user must be in.
*/
private String group;
-/**
- * Constructs the condition.
- * @param aGroup Group the user must be in.
+ /**
+ * Constructs the condition.
+ *
+ * @param aGroup
+ * Group the user must be in.
*/
public GroupUserCondition(String aGroup) {
group = aGroup;
}
-/**
- * For OR mapping.
- *
+ /**
+ * For OR mapping.
+ *
*/
protected GroupUserCondition() {
group = null;
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.UserCondition#matches(org.wamblee.usermgt.UserAccessor)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.UserCondition#matches(org.wamblee.
+ * usermgt.UserAccessor)
*/
public boolean matches(User aUser) {
return aUser.isInGroup(group);
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Returns the group.
*/
protected String getGroup() {
}
/**
- * DOCUMENT ME!
- *
- * @param aGroup The group to set.
+ *
+ * @param aGroup
+ * The group to set.
*/
protected void setGroup(String aGroup) {
group = aGroup;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#toString()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return "GroupUserCondition(group=" + group + ")";
import org.wamblee.persistence.AbstractPersistent;
-
/**
* Determiens if an operation is a subclass of a specified operation.
*/
-public class IsaOperationCondition extends AbstractPersistent
- implements OperationCondition {
+public class IsaOperationCondition extends AbstractPersistent implements
+ OperationCondition {
/**
* Operation that the other operation must be a subclass of.
*/
- private Class<?extends Operation> operation;
+ private Class<? extends Operation> operation;
-/**
+ /**
* Constructs the condition.
*
* @param aOperation
* Operation that an operation must be an instance of.
*/
- public IsaOperationCondition(Class<?extends Operation> aOperation) {
+ public IsaOperationCondition(Class<? extends Operation> aOperation) {
operation = aOperation;
}
-/**
+ /**
* For OR mapping.
*
*/
/*
* (non-Javadoc)
- *
- * @see org.wamblee.security.authorization.OperationCondition#matches(org.wamblee.security.authorization.Operation)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aOperation DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.security.authorization.OperationCondition#matches(org.wamblee
+ * .security.authorization.Operation)
*/
public boolean matches(Operation aOperation) {
return operation.isInstance(aOperation);
/**
* Gets the operation as a string. For OR mapping only.
- *
+ *
* @return Operation string.
*/
protected String getOperationString() {
/**
* Sets the operation as a string. For OR mapping only.
- *
- * @param aOperation Operation string.
- *
- * @throws IllegalArgumentException DOCUMENT ME!
+ *
+ * @param aOperation
+ * Operation string.
+ *
*/
protected void setOperationString(String aOperation) {
if (aOperation == null) {
}
try {
- operation = (Class<?extends Operation>) Class.forName(aOperation);
+ operation = (Class<? extends Operation>) Class.forName(aOperation);
} catch (Exception e) {
- throw new IllegalArgumentException("Unknown class '" + aOperation
- + "'");
+ throw new IllegalArgumentException("Unknown class '" + aOperation +
+ "'");
}
}
/*
* (non-Javadoc)
- *
+ *
* @see java.lang.Object#toString()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return "IsaOperationCondition(operation=" + operation.getName() + ")";
package org.wamblee.security.authorization;
/**
- * Represents an operation on a resource.
- * An operation should contain no state to be persisted since only the name of the
- * operation is persisted.
- *
+ * Represents an operation on a resource. An operation should contain no state
+ * to be persisted since only the name of the operation is persisted.
+ *
* @author Erik Brakkee
*/
public interface Operation {
/**
* Gets the name of the operation.
- *
+ *
* @return Operation.
*/
String getName();
import org.wamblee.persistence.Persistent;
-
/**
- * Checks if an operation matches a condition.
- *
+ * Checks if an operation matches a condition.
+ *
* @author Erik Brakkee
*/
public interface OperationCondition extends Persistent {
/**
* Determines if the operation matches.
- *
- * @param aOperation Operation.
- *
+ *
+ * @param aOperation
+ * Operation.
+ *
* @return True iff the operation matches.
*/
boolean matches(Operation aOperation);
package org.wamblee.security.authorization;
/**
- * Utility to map between a list of operations and a string based
- * on the names of the operations.
- *
+ * Utility to map between a list of operations and a string based on the names
+ * of the operations.
+ *
* @author Erik Brakkee
*/
public interface OperationRegistry {
/**
* Gets the supported operations for a given resource class.
- *
- * @param aResourceClass Resource class.
- *
+ *
+ * @param aResourceClass
+ * Resource class.
+ *
* @return Supported operations for that class.
*/
Operation[] getOperations(Class aResourceClass);
/**
* Converts a number of operations to a string.
- *
- * @param aOperations Operations to convert.
- *
+ *
+ * @param aOperations
+ * Operations to convert.
+ *
* @return String representation of the allowed operations.
*/
String encode(Operation[] aOperations);
/**
* Converts an operations string to an array of operations.
- *
- * @param aResourceClass Resource class.
- * @param aOperationsString Operations string as returned by {@link
- * #encode(Operation[])}.
- *
+ *
+ * @param aResourceClass
+ * Resource class.
+ * @param aOperationsString
+ * Operations string as returned by {@link #encode(Operation[])}.
+ *
* @return Operations array.
*/
Operation[] decode(Class aResourceClass, String aOperationsString);
/**
* Converts an operations string to an array of operations.
- *
- * @param aOperationsString Operations string as returned by {@link
- * #encode(Operation[])}.
- *
+ *
+ * @param aOperationsString
+ * Operations string as returned by {@link #encode(Operation[])}.
+ *
* @return Operations array.
*/
Operation[] decode(String aOperationsString);
import org.wamblee.persistence.Persistent;
-
/**
- * Checks if a path satisfies a condition.
- *
+ * Checks if a path satisfies a condition.
+ *
* @author Erik Brakkee
*/
public interface PathCondition extends Persistent {
/**
* Checks if the path matches the condition.
- *
- * @param aPath Path to match.
- *
+ *
+ * @param aPath
+ * Path to match.
+ *
* @return True iff the path matches.
*/
boolean matches(String aPath);
/**
* Represents a read operation on a resource.
- *
+ *
* @author Erik Brakkee
*/
public class ReadOperation extends AllOperation {
- /**
- * DOCUMENT ME!
- */
private static final String OPERATION = "read";
-/**
- * Constructs the operation.
- *
+ /**
+ * Constructs the operation.
+ *
*/
public ReadOperation() {
super(OPERATION);
import org.wamblee.persistence.AbstractPersistent;
-
/**
- * Condition to check whether a path matches a given regula expression.
- *
+ * Condition to check whether a path matches a given regula expression.
+ *
* @author Erik Brakkee
*/
-public class RegexpPathCondition extends AbstractPersistent
- implements PathCondition {
+public class RegexpPathCondition extends AbstractPersistent implements
+ PathCondition {
/**
* String the path must start with.
*/
private String pattern;
-/**
- * Constructs the condition.
- * @param aPattern String the path must start with.
+ /**
+ * Constructs the condition.
+ *
+ * @param aPattern
+ * String the path must start with.
*/
public RegexpPathCondition(String aPattern) {
pattern = aPattern;
}
-/**
- * For OR mapping.
- *
+ /**
+ * For OR mapping.
+ *
*/
protected RegexpPathCondition() {
pattern = null;
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.PathCondition#matches(java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aPath DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.PathCondition#matches(java.lang.String
+ * )
*/
public boolean matches(String aPath) {
return aPath.matches(pattern);
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Returns the _path.
*/
protected String getPattern() {
}
/**
- * DOCUMENT ME!
- *
- * @param aPattern The _path to set.
+ *
+ * @param aPattern
+ * The _path to set.
*/
protected void setPattern(String aPattern) {
pattern = aPattern;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#toString()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return "RegexpCondition(pattern = '" + pattern + "')";
/**
* Condition to check whether a path starts with a given string.
- *
+ *
* @author Erik Brakkee
*/
public class StartsWithPathCondition extends RegexpPathCondition {
-/**
- * Constructs the condition.
- * @param aPath String the path must start with.
+ /**
+ * Constructs the condition.
+ *
+ * @param aPath
+ * String the path must start with.
*/
public StartsWithPathCondition(String aPath) {
super(aPath + ".*");
}
-/**
- * For OR mapping.
- *
+ /**
+ * For OR mapping.
+ *
*/
protected StartsWithPathCondition() {
super();
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#toString()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return "StartsWithPathCondition(pattern = '" + getPattern() + "')";
import org.wamblee.usermgt.User;
-
/**
- * Utility base class for implementation of authentication rules based on
- * the
- * <ul>
- * <li>The path of the resource. To obtain the path of a resource,
- * subclasses must implement {@link #getResourcePath(Object)}. Whether a
- * path is appropriate is determined by a {@link
- * org.wamblee.security.authorization.PathCondition}.</li>
- * <li>The user identity with which the resource is accessed.
- * Whether a user is appropriate is determined by a {@link
- * org.wamblee.security.authorization.UserCondition}.</li>
- * <li>The operation that is requested. Whether the operation is
- * appropriate is determined by a {@link
- * org.wamblee.security.authorization.OperationCondition}.</li>
- * </ul>
- * In case all three conditions match, the condition returns the
- * configured result passed at construction (GRANTED or DENIED). If the
- * resource is not of the specified type, the result is UNSUPPORTED_RESOURCE,
- * otherwise, the result is UNDECIDED.
+ * Utility base class for implementation of authentication rules based on the
+ * <ul>
+ * <li>The path of the resource. To obtain the path of a resource, subclasses
+ * must implement {@link #getResourcePath(Object)}. Whether a path is
+ * appropriate is determined by a
+ * {@link org.wamblee.security.authorization.PathCondition}.</li>
+ * <li>The user identity with which the resource is accessed. Whether a user is
+ * appropriate is determined by a
+ * {@link org.wamblee.security.authorization.UserCondition}.</li>
+ * <li>The operation that is requested. Whether the operation is appropriate is
+ * determined by a {@link org.wamblee.security.authorization.OperationCondition}
+ * .</li>
+ * </ul>
+ * In case all three conditions match, the condition returns the configured
+ * result passed at construction (GRANTED or DENIED). If the resource is not of
+ * the specified type, the result is UNSUPPORTED_RESOURCE, otherwise, the result
+ * is UNDECIDED.
*/
-public abstract class UrlAuthorizationRule extends AbstractPersistent
- implements AuthorizationRule {
- /**
- * DOCUMENT ME!
- */
- private static final Logger LOGGER = Logger.getLogger(UrlAuthorizationRule.class);
+public abstract class UrlAuthorizationRule extends AbstractPersistent implements
+ AuthorizationRule {
+ private static final Logger LOGGER = Logger
+ .getLogger(UrlAuthorizationRule.class);
/**
* Result that the rule will return in case there is a match.
*/
private OperationCondition operationCondition;
-/**
- * Constructs an authorization rule.
- * IF the group and path match, then the provided result will be returned.
- * @param aResult Result of the authorization when the path and group match.
- * @param aUserCondition Condition to match users.
- * @param aPathCondition Condition to match paths with.
- * @param aResourceClass Supported resource class this is for.
- * @param aOperationCondition Condition to match the operation with.
+ /**
+ * Constructs an authorization rule. IF the group and path match, then the
+ * provided result will be returned.
+ *
+ * @param aResult
+ * Result of the authorization when the path and group match.
+ * @param aUserCondition
+ * Condition to match users.
+ * @param aPathCondition
+ * Condition to match paths with.
+ * @param aResourceClass
+ * Supported resource class this is for.
+ * @param aOperationCondition
+ * Condition to match the operation with.
*/
protected UrlAuthorizationRule(AuthorizationResult aResult,
UserCondition aUserCondition, PathCondition aPathCondition,
"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;
}
-/**
- * For OR mapping.
- *
+ /**
+ * For OR mapping.
+ *
*/
protected UrlAuthorizationRule(Class aResourceClass) {
- result = null;
- userCondition = null;
- pathCondition = null;
- resourceClass = aResourceClass;
- operationCondition = null;
+ result = null;
+ userCondition = null;
+ pathCondition = null;
+ resourceClass = aResourceClass;
+ operationCondition = null;
}
-/**
- * For OR mapping.
- *
+ /**
+ * For OR mapping.
+ *
*/
protected UrlAuthorizationRule() {
- result = null;
- userCondition = null;
- pathCondition = null;
- resourceClass = null;
- operationCondition = null;
+ result = null;
+ userCondition = null;
+ pathCondition = null;
+ resourceClass = null;
+ operationCondition = null;
}
/*
* (non-Javadoc)
- *
- * @see org.wamblee.security.authorization.AuthorizationRule#getSupportedTypes()
- */
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.security.authorization.AuthorizationRule#getSupportedTypes()
*/
public Class[] getSupportedTypes() {
return new Class[] { resourceClass };
/*
* (non-Javadoc)
- *
- * @see org.wamblee.security.authorization.AuthorizationRule#isAllowed(java.lang.Object,
- * org.wamblee.security.authorization.Operation)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aResource DOCUMENT ME!
- * @param anOperation DOCUMENT ME!
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.security.authorization.AuthorizationRule#isAllowed(java.lang
+ * .Object, org.wamblee.security.authorization.Operation)
*/
public AuthorizationResult isAllowed(Object aResource,
Operation anOperation, User aUser) {
/**
* Determines if the operation is allowed on the resource.
- *
- * @param aPath Path of the resource.
- * @param aOperation Operation to be done.
- * @param aUser Currently logged in user or null if no user is logged in.
- *
+ *
+ * @param aPath
+ * Path of the resource.
+ * @param aOperation
+ * Operation to be done.
+ * @param aUser
+ * Currently logged in user or null if no user is logged in.
+ *
* @return Authorization result,
*/
protected AuthorizationResult isAllowed(String aPath, Operation aOperation,
/**
* Gets the path of the resource.
- *
- * @param aResource Resource, guaranteed to be an instance of {@link
- * #resourceClass}.
- *
+ *
+ * @param aResource
+ * Resource, guaranteed to be an instance of
+ * {@link #resourceClass}.
+ *
* @return Path of the resource.
*/
protected abstract String getResourcePath(Object aResource);
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#toString()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
- return "UrlAUthorizationRule(result = " + result + ", pathCondition = "
- + pathCondition + ", userCondition = " + userCondition
- + ", resourceClass = " + resourceClass + ")";
+ return "UrlAUthorizationRule(result = " + result +
+ ", pathCondition = " + pathCondition + ", userCondition = " +
+ userCondition + ", resourceClass = " + resourceClass + ")";
}
/**
* Gets the authorization result for OR mapping.
- *
+ *
* @return Result.
*/
protected String getAuthorizationResultString() {
/**
* Sets the authorization result, for OR mapping.
- *
- * @param aResult Result.
+ *
+ * @param aResult
+ * Result.
*/
protected void setAuthorizationResultString(String aResult) {
result = AuthorizationResult.valueOf(aResult);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
protected String getResourceClassName() {
if (resourceClass == null) {
return "";
return resourceClass.getName();
}
- /**
- * DOCUMENT ME!
- *
- * @param aResourceClass DOCUMENT ME!
- *
- * @throws IllegalArgumentException DOCUMENT ME!
- */
protected void setResourceClassName(String aResourceClass) {
try {
resourceClass = Class.forName(aResourceClass);
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Returns the operationCondition.
*/
public OperationCondition getOperationCondition() {
}
/**
- * DOCUMENT ME!
- *
- * @param aOperationCondition The operationCondition to set.
+ *
+ * @param aOperationCondition
+ * The operationCondition to set.
*/
protected void setOperationCondition(OperationCondition aOperationCondition) {
operationCondition = aOperationCondition;
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Returns the pathCondition.
*/
public PathCondition getPathCondition() {
}
/**
- * DOCUMENT ME!
- *
- * @param aPathCondition The pathCondition to set.
+ *
+ * @param aPathCondition
+ * The pathCondition to set.
*/
protected void setPathCondition(PathCondition aPathCondition) {
pathCondition = aPathCondition;
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Returns the userCondition.
*/
public UserCondition getUserCondition() {
}
/**
- * DOCUMENT ME!
- *
- * @param aUserCondition The userCondition to set.
+ *
+ * @param aUserCondition
+ * The userCondition to set.
*/
protected void setUserCondition(UserCondition aUserCondition) {
userCondition = aUserCondition;
import org.wamblee.usermgt.User;
-
/**
- * Condition used to match a user against a specified set of users.
- *
+ * Condition used to match a user against a specified set of users.
+ *
* @author Erik Brakkee
*/
public interface UserCondition extends Persistent {
/**
* Determines if the condition matches.
- *
- * @param aUser user to check.
- *
+ *
+ * @param aUser
+ * user to check.
+ *
* @return True if the condition matches, false otherwise.
*/
boolean matches(User aUser);
/**
* Represents a write operation on a resource.
- *
+ *
* @author Erik Brakkee
*/
public class WriteOperation extends AllOperation {
- /**
- * DOCUMENT ME!
- */
private static final String OPERATION = "write";
-/**
- * Constructs the operation.
- *
+ /**
+ * Constructs the operation.
+ *
*/
public WriteOperation() {
super(OPERATION);
import org.wamblee.usermgt.hibernate.UsermgtHibernateMappingFiles;
-
/**
* Mapping files for authorization.
- *
+ *
* @author Erik Brakkee
*/
public class AuthorizationMappingFiles extends UsermgtHibernateMappingFiles {
-/**
+ /**
* Creates a new AuthorizationMappingFiles object.
*/
public AuthorizationMappingFiles() {
- super(new String[] {
- "hbm/AuthorizationRule.hbm.xml", "hbm/UserCondition.hbm.xml",
- "hbm/AuthorizationService.hbm.xml",
- "hbm/OperationCondition.hbm.xml", "hbm/PathCondition.hbm.xml",
- "hbm/TestAuthorizationRule.hbm.xml"
- });
+ super(new String[] { "hbm/AuthorizationRule.hbm.xml",
+ "hbm/UserCondition.hbm.xml", "hbm/AuthorizationService.hbm.xml",
+ "hbm/OperationCondition.hbm.xml", "hbm/PathCondition.hbm.xml",
+ "hbm/TestAuthorizationRule.hbm.xml" });
}
}
import java.util.List;
-
/**
* Authorization service with persistent storage. This is a wrapper for
- * {@link org.wamblee.security.authorization.DefaultAuthorizationService}
- * which refreshes the state of the service at certain time intervals.
- *
+ * {@link org.wamblee.security.authorization.DefaultAuthorizationService} which
+ * refreshes the state of the service at certain time intervals.
+ *
* @author Erik Brakkee
*/
public class PersistentAuthorizationService extends AbstractPersistent
*/
private long lastRefreshTime;
-/**
+ /**
* Constructs the persistent service.
*
* @param aName
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.
- *
- * @throws IllegalArgumentException DOCUMENT ME!
+ *
*/
private void initialize() {
if (service == null) {
if (result.size() > 1) {
throw new IllegalArgumentException(
- "Returned more than one service for name '" + name + "' ("
- + result.size() + ")");
+ "Returned more than one service for name '" + name + "' (" +
+ result.size() + ")");
}
if (result.size() == 0) {
/*
* (non-Javadoc)
- *
- * @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object,
- * org.wamblee.security.authorization.Operation)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aResource DOCUMENT ME!
- * @param aOperation DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.security.authorization.AuthorizationService#isAllowed(java
+ * .lang.Object, org.wamblee.security.authorization.Operation)
*/
public boolean isAllowed(Object aResource, Operation aOperation) {
initialize();
return service.isAllowed(aResource, aOperation);
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.AuthorizationService#check(T, org.wamblee.security.authorization.Operation)
- */
- /**
- * DOCUMENT ME!
- *
- * @param <T> DOCUMENT ME!
- * @param aResource DOCUMENT ME!
- * @param aOperation DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.wamblee.security.authorization.AuthorizationService#check(T,
+ * org.wamblee.security.authorization.Operation)
*/
public <T> T check(T aResource, Operation aOperation) {
initialize();
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.authorization.AuthorizationService#getRules()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public AuthorizationRule[] getRules() {
initialize();
refresh();
/*
* (non-Javadoc)
- *
- * @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aRule DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.security.authorization.AuthorizationService#appendRule(org
+ * .wamblee.security.authorization.AuthorizationRule)
*/
public void appendRule(AuthorizationRule aRule) {
initialize();
/*
* (non-Javadoc)
- *
- * @see org.wamblee.security.authorization.AuthorizationService#removeRule(int)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aIndex DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.security.authorization.AuthorizationService#removeRule(int)
*/
public void removeRule(int aIndex) {
initialize();
/*
* (non-Javadoc)
- *
- * @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int,
- * org.wamblee.security.authorization.AuthorizationRule)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aIndex DOCUMENT ME!
- * @param aRule DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.security.authorization.AuthorizationService#insertRuleAfter
+ * (int, org.wamblee.security.authorization.AuthorizationRule)
*/
public void insertRuleAfter(int aIndex, AuthorizationRule aRule) {
initialize();
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
-
/**
* MD5 Hex encoder.
- *
+ *
* @author Erik Brakkee
*/
public class Md5HexMessageDigester implements MessageDigester {
-/**
- * Constructs the message digester.
- *
+ /**
+ * Constructs the message digester.
+ *
*/
public Md5HexMessageDigester() {
// Empty
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.MessageDigester#hash(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aValue DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IllegalArgumentException DOCUMENT ME!
- */
public String hash(String aValue) {
try {
- MessageDigest digest = MessageDigest.getInstance("MD5");
- byte[] result = digest.digest(aValue.getBytes());
- char[] charResult = Hex.encodeHex(result);
+ MessageDigest digest = MessageDigest.getInstance("MD5");
+ byte[] result = digest.digest(aValue.getBytes());
+ char[] charResult = Hex.encodeHex(result);
return new String(charResult);
} catch (NoSuchAlgorithmException e) {
package org.wamblee.security.encryption;
/**
- * Utility class that encapsulates a message digest method.
+ * Utility class that encapsulates a message digest method.
*/
public interface MessageDigester {
/**
- * Computes a message digest for a value and encodes it in some
- * way.
- *
- * @param aValue Value to compute digest for.
- *
+ * Computes a message digest for a value and encodes it in some way.
+ *
+ * @param aValue
+ * Value to compute digest for.
+ *
* @return Encoded digest.
*/
String hash(String aValue);
*/
private MessageDigester passwordEncoder;
-/**
+ /**
* Creates a new AbstractUserSet object.
- *
- * @param aPasswordValidator DOCUMENT ME!
- * @param aPasswordEncoder DOCUMENT ME!
+ *
*/
protected AbstractUserSet(NameValidator aPasswordValidator,
MessageDigester aPasswordEncoder) {
- passwordValidator = aPasswordValidator;
- passwordEncoder = aPasswordEncoder;
+ passwordValidator = aPasswordValidator;
+ passwordEncoder = aPasswordEncoder;
}
/**
* Sets the password validtor and encoder in the user.
- *
- * @param aUser User.
+ *
+ * @param aUser
+ * User.
*/
protected void setPasswordInfo(User aUser) {
aUser.setPasswordValidator(passwordValidator);
aUser.setPasswordEncoder(passwordEncoder);
}
- /* (non-Javadoc)
- * @see org.wamblee.usermgt.UserSet#createUser(java.lang.String, java.lang.String, org.wamblee.usermgt.Group)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUsername DOCUMENT ME!
- * @param aPassword DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
+ /*
+ * (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);
+ passwordEncoder);
if (contains(user)) {
throw new UserMgtException(DUPLICATE_USER, user);
import java.io.Serializable;
-
/**
* Represents a group.
- *
+ *
* @author Erik Brakkee
*/
public class Group extends AbstractPersistent implements Serializable,
*/
private String name;
-/**
- * Constructs the group.
+ /**
+ * Constructs the group.
+ *
* @param aName
*/
Group(String aName) {
name = aName;
}
-/**
+ /**
* Creates a new Group object.
- *
- * @param aGroup DOCUMENT ME!
+ *
*/
public Group(Group aGroup) {
super(aGroup);
name = aGroup.name;
}
-/**
+ /**
* Creates a new Group object.
*/
protected Group() {
/**
* Gets the name of the group.
- *
+ *
* @return Group name.
*/
public String getName() {
/**
* Sets the group name.
- *
- * @param aName Group name.
+ *
+ * @param aName
+ * Group name.
*/
void setName(String aName) {
name = aName;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#equals(java.lang.Object)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean equals(Object aGroup) {
if (!(aGroup instanceof Group)) {
return name.equals(((Group) aGroup).name);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#hashCode()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public int hashCode() {
return name.hashCode();
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Comparable#compareTo(T)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public int compareTo(Object aGroup) {
return name.compareTo(((Group) aGroup).name);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#toString()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return "Group(pk = " + getPrimaryKey() + ", name=" + name + ")";
import java.util.Set;
-
/**
- * Represents a set of groups. A typical implemnetation would be, a readonly implementation
- * defined in a configuration file or a list of groups defined in a database.
- *
+ * Represents a set of groups. A typical implemnetation would be, a readonly
+ * implementation defined in a configuration file or a list of groups defined in
+ * a database.
+ *
* @author Erik Brakkee
*/
public interface GroupSet {
/**
- * Must be called when the group has been modified to notify the
- * group set.
- *
- * @param aGroup Group that was modified.
+ * Must be called when the group has been modified to notify the group set.
+ *
+ * @param aGroup
+ * Group that was modified.
*/
void groupModified(Group aGroup);
/**
* Finds the group by name.
- *
- * @param aName Group name.
- *
+ *
+ * @param aName
+ * Group name.
+ *
* @return Group or null if not found.
*/
Group find(String aName);
/**
* Determines if the group exists.
- *
- * @param aGroup Group.
- *
+ *
+ * @param aGroup
+ * Group.
+ *
* @return True iff the group exists.
*/
boolean contains(Group aGroup);
/**
- * Adds a group. If the group already exists, the existing group
- * set is left unchanged.
- *
- * @param aGroup Group.
- *
- * @return DOCUMENT ME!
+ * Adds a group. If the group already exists, the existing group set is left
+ * unchanged.
+ *
+ * @param aGroup
+ * Group.
+ *
*/
boolean add(Group aGroup);
/**
- * Removes a group. If the group does not exist, this method is a
- * no-op.
- *
- * @param aGroup Group to remove.
- *
+ * Removes a group. If the group does not exist, this method is a no-op.
+ *
+ * @param aGroup
+ * Group to remove.
+ *
* @return True if the group was removed, false otherwise.
*/
boolean remove(Group aGroup);
/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * Returns the current groups.
- * @return Groups.
+ * Returns the current groups.
+ *
+ * @return Groups.
*/
Set<Group> list();
/**
- * DOCUMENT ME!
- *
+ *
* @return The number of groups.
*/
int size();
import java.util.Set;
import java.util.TreeSet;
-
/**
* In-memory group set implementation.
- *
+ *
* @author Erik Brakkee
*/
public class InMemoryGroupSet implements GroupSet {
*/
private Set<Group> groups;
-/**
- * Constructs an empty group set.
+ /**
+ * Constructs an empty group set.
*/
public InMemoryGroupSet() {
groups = new TreeSet<Group>();
}
- /* (non-Javadoc)
- * @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group)
*/
public void groupModified(Group aGroup) {
groups.remove(aGroup);
groups.add(aGroup);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#find(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Group find(String aName) {
for (Group group : groups) {
if (group.getName().equals(aName)) {
return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean contains(Group aGroup) {
return groups.contains(aGroup);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean add(Group aGroup) {
return groups.add(aGroup);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean remove(Group aGroup) {
return groups.remove(aGroup);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#list()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Set<Group> list() {
Set<Group> list = new TreeSet<Group>();
return list;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#size()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public int size() {
return groups.size();
}
import java.util.Set;
import java.util.TreeSet;
-
/**
* In-memory user set.
- *
+ *
* @author Erik Brakkee
*/
public class InMemoryUserSet extends AbstractUserSet {
/**
- * Users. All users in this set have their password validator and
- * encoder set.
+ * Users. All users in this set have their password validator and encoder
+ * set.
*/
private Set<User> users;
-/**
+ /**
* Constructs an empty user set.
*/
public InMemoryUserSet(NameValidator aPasswordValidator,
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- */
public void userModified(User aUser) {
users.remove(aUser);
setPasswordInfo(aUser);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#find(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public User find(String aName) {
for (User user : users) {
if (user.getName().equals(aName)) {
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#add(org.wamblee.usermgt.User)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean add(User aUser) {
setPasswordInfo(aUser);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#contains(org.wamblee.usermgt.User)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean contains(User aUser) {
return users.contains(aUser);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#remove(org.wamblee.usermgt.User)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean remove(User aUser) {
return users.remove(aUser);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#list()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Set<User> list() {
Set<User> list = new TreeSet<User>();
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#list(org.wamblee.usermgt.Group)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Set<User> list(Group aGroup) {
Set<User> result = new TreeSet<User>();
return result;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.UserSet#size()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public int size() {
return users.size();
}
import javax.security.auth.Subject;
-
/**
* Implementation of the user accessor that retrieves user information from
* JAAS.
- *
+ *
* @author Erik Brakkee
*/
public class JaasUserAccessor implements UserAccessor {
*/
private Class userPrincipalClass;
-/**
- * Constructs user accessor.
- * @param aAdmin User administration.
- * @param aUserClassName Class name of the user principal.
+ /**
+ * Constructs user accessor.
+ *
+ * @param aAdmin
+ * User administration.
+ * @param aUserClassName
+ * Class name of the user principal.
*/
public JaasUserAccessor(UserAdministration aAdmin, String aUserClassName) {
admin = aAdmin;
userPrincipalClass = Class.forName(aUserClassName);
if (!Principal.class.isAssignableFrom(userPrincipalClass)) {
- throw new IllegalArgumentException("Specified class '"
- + aUserClassName + "' is not a subclass of '"
- + Principal.class.getName());
+ throw new IllegalArgumentException("Specified class '" +
+ aUserClassName + "' is not a subclass of '" +
+ Principal.class.getName());
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAccessor#getCurrentUser()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public User getCurrentUser() {
Subject subject = Subject.getSubject(AccessController.getContext());
/**
* Gets the user principal from the subject.
- *
- * @param subject Subject.
- *
+ *
+ * @param subject
+ * Subject.
+ *
* @return User principal.
- *
- * @throws IllegalArgumentException In case there is a duplicate principal
- * or the principal was not found.
+ *
+ * @throws IllegalArgumentException
+ * In case there is a duplicate principal or the principal was
+ * not found.
*/
private Principal getUserPrincipal(Subject subject) {
- Set<Principal> principals = subject.getPrincipals();
- Principal userPrincipal = null;
+ Set<Principal> principals = subject.getPrincipals();
+ Principal userPrincipal = null;
for (Principal principal : principals) {
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;
/**
* Validator of names.
- *
+ *
* @author Erik Brakkee
*/
public interface NameValidator {
/**
* Validates a name.
- *
- * @param aName Name
- *
- * @throws UserMgtException In case the name is invalid.
+ *
+ * @param aName
+ * Name
+ *
+ * @throws UserMgtException
+ * In case the name is invalid.
*/
void validate(String aName) throws UserMgtException;
}
import org.wamblee.usermgt.UserMgtException.Reason;
-
/**
* Validation of names based on a regular expression.
- *
+ *
* @author Erik Brakkee
*/
public class RegexpNameValidator implements NameValidator {
public static final String ID_PATTERN = "[a-zA-Z]+[a-zA-Z0-9]*";
/**
- * Convenience pattern for a password consisting of at least 6
- * characters.
+ * Convenience pattern for a password consisting of at least 6 characters.
*/
public static final String PASSWORD_PATTERN = ".{6}.*";
*/
private String message;
-/**
- * Validates a regular expression.
- * @param aPattern Pattern that names must comply to.
- * @param aReason Reason to report when validation fails.
- * @param aMessage Message to report.
+ /**
+ * Validates a regular expression.
+ *
+ * @param aPattern
+ * Pattern that names must comply to.
+ * @param aReason
+ * Reason to report when validation fails.
+ * @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;
}
-/**
- * Convenience constructor with all string parameters. Useful for configuration
- * in Spring.
- * @param aPattern Pattern to use.
- * @param aReason Reason.
- * @param aMessage Message.
+ /**
+ * Convenience constructor with all string parameters. Useful for
+ * configuration in Spring.
+ *
+ * @param aPattern
+ * Pattern to use.
+ * @param aReason
+ * Reason.
+ * @param aMessage
+ * Message.
*/
public RegexpNameValidator(String aPattern, String aReason, String aMessage) {
this(aPattern, Reason.valueOf(aReason), aMessage);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.NameValidator#validate(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
public void validate(String aName) throws UserMgtException {
if (!aName.matches(pattern)) {
throw new UserMgtException(reason, message);
import java.util.Set;
import java.util.TreeSet;
-
/**
* Represents a user. The methods for managing the groups of the user have
- * package scope. Managing the groups of the user should be done through the
+ * package scope. Managing the groups of the user should be done through the
* {@link org.wamblee.usermgt.UserAdministration} interface.
*/
public class User extends AbstractPersistent implements Serializable,
*/
private MessageDigester passwordEncoder;
-/**
- * Constructs the user.
- * @param aName User name.
- * @param aPassword Password.
- * @param aGroup Group the user belongs to.
+ /**
+ * Constructs the user.
+ *
+ * @param aName
+ * User name.
+ * @param aPassword
+ * Password.
+ * @param aGroup
+ * Group the user belongs to.
*/
User(String aName, String aPassword, Group aGroup,
NameValidator aPasswordValidator, MessageDigester aPasswordEncoder)
super();
name = aName;
aPasswordValidator.validate(aPassword);
- password = aPasswordEncoder.hash(aPassword);
- groups = new TreeSet<Group>();
+ password = aPasswordEncoder.hash(aPassword);
+ groups = new TreeSet<Group>();
groups.add(aGroup);
- passwordValidator = aPasswordValidator;
- passwordEncoder = aPasswordEncoder;
+ passwordValidator = aPasswordValidator;
+ passwordEncoder = aPasswordEncoder;
}
-/**
+ /**
* Creates a new User object.
- *
- * @param aUser DOCUMENT ME!
+ *
*/
public User(User aUser) {
super(aUser);
- name = aUser.name;
- password = aUser.password;
- groups = new TreeSet<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;
}
-/**
+ /**
* Creates a new User object.
*/
User() {
super();
- name = null;
- password = null;
- groups = null;
- passwordValidator = null;
- passwordEncoder = null;
+ name = null;
+ password = null;
+ groups = null;
+ passwordValidator = null;
+ passwordEncoder = null;
}
/**
* Sets the password validator.
- *
- * @param aPasswordValidator Validator.
+ *
+ * @param aPasswordValidator
+ * Validator.
*/
public void setPasswordValidator(NameValidator aPasswordValidator) {
passwordValidator = aPasswordValidator;
/**
* Sets the password encoder.
- *
- * @param aPasswordEncoder Encoder.
+ *
+ * @param aPasswordEncoder
+ * Encoder.
*/
public void setPasswordEncoder(MessageDigester aPasswordEncoder) {
passwordEncoder = aPasswordEncoder;
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Returns the password.
*/
String getPassword() {
/**
* Checks the password.
- *
- * @param aPassword Password to check.
- *
- * @throws UserMgtException In case the password is incorrect.
+ *
+ * @param aPassword
+ * Password to check.
+ *
+ * @throws UserMgtException
+ * In case the password is incorrect.
*/
public void checkPassword(String aPassword) throws UserMgtException {
String encoded = passwordEncoder.hash(aPassword);
/**
* Changes the password.
- *
- * @param aOldPassword Old password.
- * @param aNewPassword New password.
- *
- * @throws UserMgtException In case the old password is incorrect.
+ *
+ * @param aOldPassword
+ * Old password.
+ * @param aNewPassword
+ * New password.
+ *
+ * @throws UserMgtException
+ * In case the old password is incorrect.
*/
public void changePassword(String aOldPassword, String aNewPassword)
throws UserMgtException {
}
/**
- * DOCUMENT ME!
- *
- * @param aPassword The password to set.
- *
- * @throws UserMgtException DOCUMENT ME!
+ *
+ * @param aPassword
+ * The password to set.
+ *
*/
public void setPassword(String aPassword) throws UserMgtException {
passwordValidator.validate(aPassword);
/**
* For OR mapping.
- *
+ *
* @return Password.
*/
protected String getPasswordString() {
/**
* For OR mapping.
- *
- * @param aPassword Password.
+ *
+ * @param aPassword
+ * Password.
*/
protected void setPasswordString(String aPassword) {
password = aPassword;
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Returns the _user.
*/
public String getName() {
}
/**
- * DOCUMENT ME!
- *
- * @param aName The username to set.
+ *
+ * @param aName
+ * The username to set.
*/
void setName(String aName) {
name = aName;
/**
* Gets the groups the user belongs to.
- *
+ *
* @return Groups.
*/
public Set<Group> getGroups() {
/**
* Checks whether the user belongs to the given group.
- *
- * @param aGroup Group.
- *
+ *
+ * @param aGroup
+ * Group.
+ *
* @return True if the user belongs to the group.
*/
public boolean isInGroup(Group aGroup) {
/**
* Checks whether the user belongs to the given group.
- *
- * @param aGroup Group.
- *
+ *
+ * @param aGroup
+ * Group.
+ *
* @return True if the user belongs to the group.
*/
public boolean isInGroup(String aGroup) {
}
/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * Gets the group set. For OR mapping.
- * @return set of groups.
+ * Gets the group set. For OR mapping.
+ *
+ * @return set of groups.
*/
Set<Group> getGroupSet() {
return groups;
/**
* Sets the groups the user belongs to, for OR mapping.
- *
- * @param aGroups Groups.
+ *
+ * @param aGroups
+ * Groups.
*/
void setGroupSet(Set<Group> aGroups) {
groups = aGroups;
/**
* Adds the user to a group.
- *
- * @param aGroup Group to add the user to.
- *
- * @throws UserMgtException In case the user already belongs to the group.
+ *
+ * @param aGroup
+ * Group to add the user to.
+ *
+ * @throws UserMgtException
+ * In case the user already belongs to the group.
*/
void addGroup(Group aGroup) throws UserMgtException {
if (groups.contains(aGroup)) {
/**
* Removes the user from a group.
- *
- * @param aGroup Group.
- *
- * @throws UserMgtException In case the user does not belong to the group.
+ *
+ * @param aGroup
+ * Group.
+ *
+ * @throws UserMgtException
+ * In case the user does not belong to the group.
*/
void removeGroup(Group aGroup) throws UserMgtException {
if (!groups.contains(aGroup)) {
groups.remove(aGroup);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#equals(java.lang.Object)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean equals(Object aUser) {
if (!(aUser instanceof User)) {
return name.equals(user.name);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#hashCode()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public int hashCode() {
return name.hashCode();
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#toString()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
String result = "User(name=" + name + ", password=" + password;
return result + ")";
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Comparable#compareTo(T)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public int compareTo(Object aUser) {
return name.compareTo(((User) aUser).name);
}
package org.wamblee.usermgt;
/**
- * Interface for accessing the currently logged in user.
- *
+ * Interface for accessing the currently logged in user.
+ *
* @author Erik Brakkee
*/
public interface UserAccessor {
/**
* Gets the current user.
- *
+ *
* @return Currently logged in user or null if no user is found.
*/
User getCurrentUser();
import java.security.NoSuchAlgorithmException;
-
/**
- * User administration initializer. It populates the user administration
- * with a number of groups and users but only in case no users exist.
- *
+ * User administration initializer. It populates the user administration with a
+ * number of groups and users but only in case no users exist.
+ *
* @author Erik Brakkee
*/
public class UserAdminInitializer {
- /**
- * DOCUMENT ME!
- */
- private static final Logger LOGGER = Logger.getLogger(UserAdminInitializer.class);
+ private static final Logger LOGGER = Logger
+ .getLogger(UserAdminInitializer.class);
-/**
+ /**
* Initializes the user administration in case no users are present.
*
*/
public UserAdminInitializer(UserAdministration aAdmin, String[] aUsers,
- String[] aGroups, String[] aPasswords)
- throws UserMgtException, NoSuchAlgorithmException {
- if ((aUsers.length != aGroups.length)
- || (aUsers.length != aPasswords.length)) {
+ String[] aGroups, String[] aPasswords) throws UserMgtException,
+ NoSuchAlgorithmException {
+ if ((aUsers.length != aGroups.length) ||
+ (aUsers.length != aPasswords.length)) {
throw new IllegalArgumentException(
- "Array sizes for users, groups, and passwords differ: "
- + aUsers.length + "," + aGroups.length + ","
- + aPasswords.length);
+ "Array sizes for users, groups, and passwords differ: " +
+ aUsers.length + "," + aGroups.length + "," +
+ aPasswords.length);
}
if (aAdmin.getUserCount() == 0) {
/**
* Adds the specified users and groups to the user administration.
- *
- * @param aAdmin User administration.
- * @param aUsers Users.
- * @param aGroups Groups.
- * @param aPasswords Passwords.
- *
- * @throws UserMgtException In case of a problem creating users or groups.
+ *
+ * @param aAdmin
+ * User administration.
+ * @param aUsers
+ * Users.
+ * @param aGroups
+ * Groups.
+ * @param aPasswords
+ * Passwords.
+ *
+ * @throws UserMgtException
+ * In case of a problem creating users or groups.
*/
private void initialize(UserAdministration aAdmin, String[] aUsers,
String[] aGroups, String[] aPasswords) throws UserMgtException {
for (int i = 0; i < aUsers.length; i++) {
- String user = aUsers[i];
- String group = aGroups[i];
+ String user = aUsers[i];
+ String group = aGroups[i];
String password = aPasswords[i];
if (aAdmin.getUser(user) == null) {
}
assert groupObj != null;
- LOGGER.info("Creating user: " + user + " password: " + password);
+ LOGGER
+ .info("Creating user: " + user + " password: " + password);
aAdmin.createUser(user, password, groupObj);
}
}
import java.util.Set;
-
/**
- * Interface for user administration. Manages the users and groups.
- *
+ * Interface for user administration. Manages the users and groups.
+ *
* @author Erik Brakkee
*/
public interface UserAdministration {
/**
* Creates a new user.
- *
- * @param aUser Username.
- * @param aPassword Password.
- * @param aGroup Group.
- *
+ *
+ * @param aUser
+ * Username.
+ * @param aPassword
+ * Password.
+ * @param aGroup
+ * Group.
+ *
* @return User.
- *
- * @throws UserMgtException In case there is a conflict with an existing
- * user.
+ *
+ * @throws UserMgtException
+ * In case there is a conflict with an existing user.
*/
User createUser(String aUser, String aPassword, Group aGroup)
throws UserMgtException;
/**
* Creates a new group.
- *
- * @param aName Group name.
- *
+ *
+ * @param aName
+ * Group name.
+ *
* @return Group
- *
- * @throws UserMgtException In case there is a conflict with an existing
- * group.
+ *
+ * @throws UserMgtException
+ * In case there is a conflict with an existing group.
*/
Group createGroup(String aName) throws UserMgtException;
/**
- * DOCUMENT ME!
- *
+ *
* @return Number of users.
*/
int getUserCount();
/**
- * DOCUMENT ME!
- *
+ *
* @return Number of groups.
*/
int getGroupCount();
/**
* Must be called when the user is modified.
- *
- * @param aUser User.
+ *
+ * @param aUser
+ * User.
*/
void userModified(User aUser);
/**
* Must be called when the group is modified.
- *
- * @param aGroup Group.
+ *
+ * @param aGroup
+ * Group.
*/
void groupModified(Group aGroup);
/**
* Gets the user for a given name.
- *
- * @param aName User name.
- *
+ *
+ * @param aName
+ * User name.
+ *
* @return User or null if not found.
*/
User getUser(String aName);
/**
* Gets the group for a given group name.
- *
- * @param aName Group name.
- *
+ *
+ * @param aName
+ * Group name.
+ *
* @return Group or null if not found.
*/
Group getGroup(String aName);
/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * Get the users.
- * @return All known users.
+ * Get the users.
+ *
+ * @return All known users.
*/
Set<User> getUsers();
/**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * Gets the users for a given group.
- * @param aGroup Group.
+ * Gets the users for a given group.
+ *
+ * @param aGroup
+ * Group.
* @return Set of users (always non-null).
*/
Set<User> getUsers(Group aGroup);
/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * Gets all known groups.
- * @return Groups.
+ * Gets all known groups.
+ *
+ * @return Groups.
*/
Set<Group> getGroups();
/**
* Renames a user.
- *
- * @param aUser User object for which user name must be changed.
- * @param aUserName New user name.
- *
- * @throws UserMgtException In case the user is not known or the new user
- * name is already in use by another user.
+ *
+ * @param aUser
+ * User object for which user name must be changed.
+ * @param aUserName
+ * New user name.
+ *
+ * @throws UserMgtException
+ * In case the user is not known or the new user name is already
+ * in use by another user.
*/
void renameUser(User aUser, String aUserName) throws UserMgtException;
/**
* Renames a group.
- *
- * @param aGroup Group to rename.
- * @param aGroupName New name for the group.
- *
- * @throws UserMgtException In case the new group name is already used by
- * another group of if the existing group is unknown.
+ *
+ * @param aGroup
+ * Group to rename.
+ * @param aGroupName
+ * New name for the group.
+ *
+ * @throws UserMgtException
+ * In case the new group name is already used by another group
+ * of if the existing group is unknown.
*/
void renameGroup(Group aGroup, String aGroupName) throws UserMgtException;
/**
* Removes the user.
- *
- * @param aUser User to remove.
- *
- * @throws UserMgtException In case the user does not exist.
+ *
+ * @param aUser
+ * User to remove.
+ *
+ * @throws UserMgtException
+ * In case the user does not exist.
*/
void removeUser(User aUser) throws UserMgtException;
/**
* Removes the group.
- *
- * @param aGroup Group to remove.
- *
- * @throws UserMgtException In case there are still users that are in the
- * given group.
+ *
+ * @param aGroup
+ * Group to remove.
+ *
+ * @throws UserMgtException
+ * In case there are still users that are in the given group.
*/
void removeGroup(Group aGroup) throws UserMgtException;
/**
* Adds a user to a group.
- *
- * @param aUser User.
- * @param aGroup Group.
- *
- * @throws UserMgtException In case the user or group or not known or if
- * the user is already part of the group.
+ *
+ * @param aUser
+ * User.
+ * @param aGroup
+ * Group.
+ *
+ * @throws UserMgtException
+ * In case the user or group or not known or if the user is
+ * already part of the group.
*/
void addUserToGroup(User aUser, Group aGroup) throws UserMgtException;
/**
* Removes a user from a group.
- *
- * @param aUser User
- * @param aGroup Group
- *
- * @throws UserMgtException In case the user or group are unknown or if the
- * user is not part of the group.
- */
- void removeUserFromGroup(User aUser, Group aGroup)
- throws UserMgtException;
+ *
+ * @param aUser
+ * User
+ * @param aGroup
+ * Group
+ *
+ * @throws UserMgtException
+ * In case the user or group are unknown or if the user is not
+ * part of the group.
+ */
+ void removeUserFromGroup(User aUser, Group aGroup) throws UserMgtException;
}
import java.util.Set;
-
/**
* Administration of users and groups.
- *
+ *
* @author Erik Brakkee
*/
public class UserAdministrationImpl implements UserAdministration {
*/
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;
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#createUser(java.lang.String,
- * java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- * @param aPassword DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
+ * java.lang.String)
*/
public User createUser(String aUser, String aPassword, Group aGroup)
throws UserMgtException {
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#createGroup(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
public Group createGroup(String aName) throws UserMgtException {
groupValidator.validate(aName);
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.UserAdministration#userModified(org.wamblee.usermgt.User)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.UserAdministration#userModified(org.wamblee.usermgt
+ * .User)
*/
public void userModified(User aUser) {
users.userModified(aUser);
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.UserAdministration#groupModified(org.wamblee.usermgt.Group)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.UserAdministration#groupModified(org.wamblee.usermgt
+ * .Group)
*/
public void groupModified(Group aGroup) {
groups.groupModified(aGroup);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#getUser(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public User getUser(String aName) {
return users.find(aName);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#getGroup(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Group getGroup(String aName) {
return groups.find(aName);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#getUsers()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Set<User> getUsers() {
return users.list();
}
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.UserAdministration#getUsers(org.wamblee.usermgt.Group)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.UserAdministration#getUsers(org.wamblee.usermgt.Group
+ * )
*/
public Set<User> getUsers(Group aGroup) {
return users.list(aGroup);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#getGroups()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Set<Group> getGroups() {
return groups.list();
}
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.UserAdministration#removeUser(org.wamblee.usermgt.User)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.UserAdministration#removeUser(org.wamblee.usermgt
+ * .User)
*/
public void removeUser(User aUser) throws UserMgtException {
checkUser(aUser);
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.UserAdministration#removeGroup(org.wamblee.usermgt.Group)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.UserAdministration#removeGroup(org.wamblee.usermgt
+ * .Group)
*/
public void removeGroup(Group aGroup) throws UserMgtException {
checkGroup(aGroup);
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.UserAdministration#renameUser(org.wamblee.usermgt.User,
- * java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- * @param aUserName DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.UserAdministration#renameUser(org.wamblee.usermgt
+ * .User, java.lang.String)
*/
public void renameUser(User aUser, String aUserName)
throws UserMgtException {
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.UserAdministration#renameGroup(org.wamblee.usermgt.Group,
- * java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- * @param aGroupName DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.UserAdministration#renameGroup(org.wamblee.usermgt
+ * .Group, java.lang.String)
*/
public void renameGroup(Group aGroup, String aGroupName)
throws UserMgtException {
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.UserAdministration#addUserToGroup(org.wamblee.usermgt.User,
- * org.wamblee.usermgt.Group)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.UserAdministration#addUserToGroup(org.wamblee.usermgt
+ * .User, org.wamblee.usermgt.Group)
*/
public void addUserToGroup(User aUser, Group aGroup)
throws UserMgtException {
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.UserAdministration#removeUserFromGroup(org.wamblee.usermgt.User,
- * org.wamblee.usermgt.Group)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.UserAdministration#removeUserFromGroup(org.wamblee
+ * .usermgt.User, org.wamblee.usermgt.Group)
*/
public void removeUserFromGroup(User aUser, Group aGroup)
throws UserMgtException {
}
/**
- * DOCUMENT ME!
- *
+ *
* @param aUser
- *
+ *
* @throws UserMgtException
*/
private void checkUser(User aUser) throws UserMgtException {
}
/**
- * DOCUMENT ME!
- *
+ *
* @param aGroup
- *
+ *
* @throws UserMgtException
*/
private void checkGroup(Group aGroup) throws UserMgtException {
}
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.UserAdministration#getUserCount()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public int getUserCount() {
return users.size();
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.UserAdministration#getGroupCount()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public int getGroupCount() {
return groups.size();
}
import java.util.Map;
import java.util.TreeMap;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class UserGroupRepositoryComponent extends SpringComponent {
-/**
+ /**
* Creates a new UserGroupRepositoryComponent object.
- *
- * @param aName DOCUMENT ME!
+ *
*/
public UserGroupRepositoryComponent(String aName) {
- super(aName,
+ super(
+ aName,
new String[] { "spring/org.wamblee.security.usermgt-repositories.xml" },
createProvided(), createRequired());
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static Map<RequiredInterface, String> createRequired() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
required.put(new DefaultRequiredInterface("sessionFactory",
- SessionFactory.class), "sessionFactory");
+ SessionFactory.class), "sessionFactory");
return required;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static Map<String, ProvidedInterface> createProvided() {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("userCache",
- new DefaultProvidedInterface("cache", EhCache.class));
- provided.put(UserSet.class.getName(),
- new DefaultProvidedInterface("userset", UserSet.class));
- provided.put(GroupSet.class.getName(),
- new DefaultProvidedInterface("groupset", GroupSet.class));
+ provided.put("userCache", new DefaultProvidedInterface("cache",
+ EhCache.class));
+ provided.put(UserSet.class.getName(), new DefaultProvidedInterface(
+ "userset", UserSet.class));
+ provided.put(GroupSet.class.getName(), new DefaultProvidedInterface(
+ "groupset", GroupSet.class));
return provided;
}
import java.util.EnumMap;
-
/**
* User management exception.
- *
+ *
* @author Erik Brakkee
*/
public class UserMgtException extends Exception {
- /**
- * DOCUMENT ME!
- */
static final long serialVersionUID = 5585349754997507529L;
/**
* Mapping of enum to exception message text.
*/
- private static final EnumMap<Reason, String> MESSAGES = new EnumMap<Reason, String>(Reason.class);
+ private static final EnumMap<Reason, String> MESSAGES = new EnumMap<Reason, String>(
+ Reason.class);
static {
MESSAGES.put(Reason.UNKNOWN_USER, "Unknown user");
*/
private Group group;
-/**
+ /**
* Creates a new UserMgtException object.
- *
- * @param aCause DOCUMENT ME!
- * @param aMessage DOCUMENT ME!
+ *
*/
public UserMgtException(Reason aCause, String aMessage) {
super(MESSAGES.get(aCause) + ": " + aMessage);
cause = aCause;
}
-/**
+ /**
* Creates a new UserMgtException object.
- *
- * @param aCause DOCUMENT ME!
- * @param aUser DOCUMENT ME!
+ *
*/
public UserMgtException(Reason aCause, User aUser) {
this(aCause, "for user '" + aUser.getName() + "'");
user = aUser;
}
-/**
+ /**
* Creates a new UserMgtException object.
- *
- * @param aCause DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
+ *
*/
public UserMgtException(Reason aCause, Group aGroup) {
this(aCause, "for group '" + aGroup.getName() + "'");
group = aGroup;
}
-/**
+ /**
* Creates a new UserMgtException object.
- *
- * @param aCause DOCUMENT ME!
- * @param aUser DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
+ *
*/
public UserMgtException(Reason aCause, User aUser, Group aGroup) {
- this(aCause,
- "for user '" + aUser.getName() + "' and group '" + aGroup.getName()
- + "'");
- user = aUser;
- group = aGroup;
+ this(aCause, "for user '" + aUser.getName() + "' and group '" +
+ aGroup.getName() + "'");
+ user = aUser;
+ group = aGroup;
}
/**
* Gets the cause of the problem.
- *
+ *
* @return Cause.
*/
public Reason getReason() {
/**
* Gets the user for which the problem occurred.
- *
+ *
* @return User or null if not applicable.
*/
public User getUser() {
/**
* Gets the group for which the problem occured.
- *
+ *
* @return Group or null if not applicable.
*/
public Group getGroup() {
return group;
}
-/**
- * Possible causes for the exception.
- *
+ /**
+ * Possible causes for the exception.
+ *
*/
- public enum Reason {UNKNOWN_USER,
- UNKNOWN_GROUP,
- DUPLICATE_USER,
- DUPLICATE_GROUP,
- USER_ALREADY_IN_GROUP,
- USER_NOT_IN_GROUP,
- TRIVIAL_RENAME,
- INVALID_PASSWORD,
- GROUP_STILL_OCCUPIED,
- USER_MUST_BE_IN_A_GROUP,
- INVALID_USERNAME,
- INVALID_GROUPNAME;
+ public enum Reason {
+ UNKNOWN_USER, UNKNOWN_GROUP, DUPLICATE_USER, DUPLICATE_GROUP, USER_ALREADY_IN_GROUP, USER_NOT_IN_GROUP, TRIVIAL_RENAME, INVALID_PASSWORD, GROUP_STILL_OCCUPIED, USER_MUST_BE_IN_A_GROUP, INVALID_USERNAME, INVALID_GROUPNAME;
}
}
import java.util.Set;
-
/**
- * Represents a set of users.
- * Typical implementations would be an implementation based on a static configuration file or
- * an implementation backed by a database.
- *
+ * Represents a set of users. Typical implementations would be an implementation
+ * based on a static configuration file or an implementation backed by a
+ * database.
+ *
* @author Erik Brakkee
*/
public interface UserSet {
/**
* Creates a user.
- *
- * @param aUsername User name.
- * @param aPassword Password.
- * @param aGroup Group.
- *
+ *
+ * @param aUsername
+ * User name.
+ * @param aPassword
+ * Password.
+ * @param aGroup
+ * Group.
+ *
* @return New user.
- *
- * @throws UserMgtException In case the user cannot be created.
+ *
+ * @throws UserMgtException
+ * In case the user cannot be created.
*/
User createUser(String aUsername, String aPassword, Group aGroup)
throws UserMgtException;
/**
- * Must be called whenever a user object has been modified to
- * notify the user set.
- *
- * @param aUser Modified user.
+ * Must be called whenever a user object has been modified to notify the
+ * user set.
+ *
+ * @param aUser
+ * Modified user.
*/
void userModified(User aUser);
/**
- * Finds user.
- *
- * @param aName Username.
- *
+ * Finds user.
+ *
+ * @param aName
+ * Username.
+ *
* @return User or null if not found.
*/
User find(String aName);
/**
* Checks if a user exists.
- *
- * @param aUser User.
- *
+ *
+ * @param aUser
+ * User.
+ *
* @return True iff the user exists.
*/
boolean contains(User aUser);
/**
- * Adds a user. If the user already exists, the user details are
- * updated with that of the specified user object.
- *
- * @param aUser User to add.
- *
- * @return DOCUMENT ME!
+ * Adds a user. If the user already exists, the user details are updated
+ * with that of the specified user object.
+ *
+ * @param aUser
+ * User to add.
+ *
*/
boolean add(User aUser);
/**
* Removes a user. If the user does not exist, nothing happens.
- *
+ *
* @param aUser
- *
- * @return DOCUMENT ME!
+ *
*/
boolean remove(User aUser);
/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * Lists the current users.
- * @return Users.
+ * Lists the current users.
+ *
+ * @return Users.
*/
Set<User> list();
/**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * Lists the users belonging to a particular group.
- * @param aGroup Group.
- * @return Groups.
+ * Lists the users belonging to a particular group.
+ *
+ * @param aGroup
+ * Group.
+ * @return Groups.
*/
Set<User> list(Group aGroup);
/**
- * DOCUMENT ME!
- *
+ *
* @return The number of users.
*/
int size();
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class AuthorizationComponent extends DefaultContainer {
- /**
- * DOCUMENT ME!
- */
- private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface("transactionManager",
- PlatformTransactionManager.class);
+ private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface(
+ "transactionManager", PlatformTransactionManager.class);
- /**
- * DOCUMENT ME!
- */
- private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface("hibernateTemplate",
- HibernateTemplate.class);
+ private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface(
+ "hibernateTemplate", HibernateTemplate.class);
- /**
- * DOCUMENT ME!
- */
- private ProvidedInterface AUTHORIZATION_SERVICE = new DefaultProvidedInterface("authorizationService",
- AuthorizationService.class);
+ private ProvidedInterface AUTHORIZATION_SERVICE = new DefaultProvidedInterface(
+ "authorizationService", AuthorizationService.class);
-/**
+ /**
* Creates a new AuthorizationComponent object.
- *
- * @param aName DOCUMENT ME!
- * @param aExposeInternals DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
+ *
+ *
*/
public AuthorizationComponent(String aName, boolean aExposeInternals)
throws IOException {
super(aName);
- ObjectConfiguration authConfig = new ObjectConfiguration(AuthorizationMappingFiles.class);
+ ObjectConfiguration authConfig = new ObjectConfiguration(
+ AuthorizationMappingFiles.class);
authConfig.getSetterConfig().initAllSetters();
- addComponent("mappingFiles", new AuthorizationMappingFiles(), authConfig);
+ addComponent("mappingFiles", new AuthorizationMappingFiles(),
+ authConfig);
Component<?> hibernate = new HibernateComponent("hibernate");
addComponent(hibernate);
Component<?> authorization = new AuthorizationLightComponent(
- "authorization");
+ "authorization");
addComponent(authorization);
addRequiredInterface(new DefaultRequiredInterface("datasource",
- DataSource.class));
+ DataSource.class));
addRequiredInterface(new DefaultRequiredInterface("userAccessor",
- UserAccessor.class));
+ UserAccessor.class));
addRequiredInterface(new DefaultRequiredInterface("ormconfig",
- ORMappingConfig.class));
+ ORMappingConfig.class));
if (aExposeInternals) {
addProvidedInterface(TRANSACTION_MGR);
import java.util.HashMap;
import java.util.Map;
-
/**
- * Light version of the user administration component that requires
- * external datasource, and userset and group set components, as well as an
- * external hibernate session factory.
- *
+ * Light version of the user administration component that requires external
+ * datasource, and userset and group set components, as well as an external
+ * hibernate session factory.
+ *
* @author Erik Brakkee
*/
public class AuthorizationLightComponent extends SpringComponent {
-/**
+ /**
* Creates a new AuthorizationLightComponent object.
- *
- * @param aName DOCUMENT ME!
+ *
*/
public AuthorizationLightComponent(String aName) {
super(aName,
createProvided(), createRequired());
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static Map<RequiredInterface, String> createRequired() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
required.put(new DefaultRequiredInterface("userArccessor",
- UserAccessor.class), UserAccessor.class.getName());
+ UserAccessor.class), UserAccessor.class.getName());
required.put(new DefaultRequiredInterface("hibernateTemplate",
- HibernateTemplate.class), HibernateTemplate.class.getName());
+ HibernateTemplate.class), HibernateTemplate.class.getName());
return required;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static Map<String, ProvidedInterface> createProvided() {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
provided.put(AuthorizationService.class.getName(),
import java.util.Set;
import java.util.TreeSet;
-
/**
* Set of groups backed by the database.
- *
+ *
* @author Erik Brakkee
*/
public class HibernateGroupSet extends HibernateSupport implements GroupSet {
- /**
- * DOCUMENT ME!
- */
private static final String QUERY_FIND_BY_NAME = "findGroupByName";
- /**
- * DOCUMENT ME!
- */
private static final String PARAM_NAME = "name";
- /**
- * DOCUMENT ME!
- */
private static final String QUERY_COUNT_GROUPS = "countGroups";
-/**
+ /**
* Creates a new HibernateGroupSet object.
*/
public HibernateGroupSet() {
// Empty
}
- /* (non-Javadoc)
- * @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group)
*/
public void groupModified(Group aGroup) {
assert aGroup.getPrimaryKey() != null;
super.merge(aGroup);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#find(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws RuntimeException DOCUMENT ME!
- */
public Group find(String aName) {
- List list = getHibernateTemplate()
- .findByNamedQueryAndNamedParam(QUERY_FIND_BY_NAME, PARAM_NAME, aName);
+ List list = getHibernateTemplate().findByNamedQueryAndNamedParam(
+ QUERY_FIND_BY_NAME, PARAM_NAME, aName);
if (list.size() > 1) {
throw new RuntimeException(
return new Group((Group) list.get(0));
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean contains(Group aGroup) {
return find(aGroup.getName()) != null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean add(Group aGroup) {
assert aGroup.getPrimaryKey() == null;
return true;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean remove(Group aGroup) {
assert aGroup.getPrimaryKey() != null;
return true;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#list()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Set<Group> list() {
- Set<Group> groups = new TreeSet<Group>();
- List<Group> list = getHibernateTemplate().loadAll(Group.class);
+ Set<Group> groups = new TreeSet<Group>();
+ List<Group> list = getHibernateTemplate().loadAll(Group.class);
for (Group group : list) {
groups.add(new Group(group));
return groups;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.GroupSet#size()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public int size() {
- Long result = (Long) getHibernateTemplate()
- .findByNamedQuery(QUERY_COUNT_GROUPS).get(0);
+ Long result = (Long) getHibernateTemplate().findByNamedQuery(
+ QUERY_COUNT_GROUPS).get(0);
return result.intValue();
}
import java.util.Set;
import java.util.TreeSet;
-
/**
* User set backed by the database.
- *
+ *
* @author Erik Brakkee
*/
public class HibernateUserSet extends AbstractUserSet {
- /**
- * DOCUMENT ME!
- */
private static final String QUERY_FIND_BY_NAME = "findUserByName";
- /**
- * DOCUMENT ME!
- */
private static final String QUERY_FIND_BY_GROUP_NAME = "findUserByGroupName";
- /**
- * DOCUMENT ME!
- */
private static final String PARAM_NAME = "name";
- /**
- * DOCUMENT ME!
- */
private static final String QUERY_COUNT_USERS = "countUsers";
/**
- * Cache of users. Every user in the cache has its password
- * validator and encoder set.
+ * Cache of users. Every user in the cache has its password validator and
+ * encoder set.
*/
private Cache<String, User> cache;
*/
private HibernateSupport hibernateSupport;
-/**
+ /**
* Constructs a user set backed by the database.
- * @param aCache User cache to use.
+ *
+ * @param aCache
+ * User cache to use.
*/
public HibernateUserSet(Cache<String, User> aCache,
NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) {
super(aPasswordValidator, aPasswordEncoder);
- cache = aCache;
- hibernateSupport = new HibernateSupport();
+ cache = aCache;
+ hibernateSupport = new HibernateSupport();
}
/**
* Sets the session factory.
- *
- * @param aFactory Session factory.
+ *
+ * @param aFactory
+ * Session factory.
*/
public void setSessionFactory(SessionFactory aFactory) {
hibernateSupport.setSessionFactory(aFactory);
/**
* Gets the hibernate template.
- *
+ *
* @return Hibernate template.
*/
private HibernateTemplate getHibernateTemplate() {
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- */
public void userModified(User aUser) {
assert aUser.getPrimaryKey() != null;
hibernateSupport.merge(aUser);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#find(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws RuntimeException DOCUMENT ME!
- */
public User find(String aName) {
User user = cache.get(aName);
return user;
}
- List result = getHibernateTemplate()
- .findByNamedQueryAndNamedParam(QUERY_FIND_BY_NAME, PARAM_NAME, aName);
+ List result = getHibernateTemplate().findByNamedQueryAndNamedParam(
+ QUERY_FIND_BY_NAME, PARAM_NAME, aName);
if (result.size() > 1) {
throw new RuntimeException(
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#contains(org.wamblee.usermgt.User)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean contains(User aUser) {
return find(aUser.getName()) != null;
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#add(org.wamblee.usermgt.User)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean add(User aUser) {
assert aUser.getPrimaryKey() == null;
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#remove(org.wamblee.usermgt.User)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean remove(User aUser) {
assert aUser.getPrimaryKey() != null;
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#list()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Set<User> list() {
- Set<User> users = new TreeSet<User>();
- List<User> list = getHibernateTemplate().loadAll(User.class);
+ Set<User> users = new TreeSet<User>();
+ List<User> list = getHibernateTemplate().loadAll(User.class);
for (User user : list) {
setPasswordInfo(user);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#list(org.wamblee.usermgt.Group)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Set<User> list(Group aGroup) {
- Set<User> users = new TreeSet<User>();
- List<User> list = getHibernateTemplate()
- .findByNamedQueryAndNamedParam(QUERY_FIND_BY_GROUP_NAME,
- PARAM_NAME, aGroup.getName());
+ Set<User> users = new TreeSet<User>();
+ List<User> list = getHibernateTemplate().findByNamedQueryAndNamedParam(
+ QUERY_FIND_BY_GROUP_NAME, PARAM_NAME, aGroup.getName());
for (User user : list) {
setPasswordInfo(user);
return users;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.UserSet#size()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public int size() {
- Long result = (Long) getHibernateTemplate()
- .findByNamedQuery(QUERY_COUNT_USERS).get(0);
+ Long result = (Long) getHibernateTemplate().findByNamedQuery(
+ QUERY_COUNT_USERS).get(0);
return result.intValue();
}
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class UserAdministrationComponent extends DefaultContainer {
- /**
- * DOCUMENT ME!
- */
- private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface("transactionManager",
- PlatformTransactionManager.class);
+ private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface(
+ "transactionManager", PlatformTransactionManager.class);
- /**
- * DOCUMENT ME!
- */
- private ProvidedInterface USER_CACHE = new DefaultProvidedInterface("userCache",
- EhCache.class);
+ private ProvidedInterface USER_CACHE = new DefaultProvidedInterface(
+ "userCache", EhCache.class);
- /**
- * DOCUMENT ME!
- */
- private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface("hibernateTemplate",
- HibernateTemplate.class);
+ private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface(
+ "hibernateTemplate", HibernateTemplate.class);
- /**
- * DOCUMENT ME!
- */
- private ProvidedInterface USER_MGT = new DefaultProvidedInterface("usermgt",
- UserAdministration.class);
+ private ProvidedInterface USER_MGT = new DefaultProvidedInterface(
+ "usermgt", UserAdministration.class);
-/**
+ /**
* Creates a new UserAdministrationComponent object.
- *
- * @param aName DOCUMENT ME!
- * @param aExposeInternals DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
+ *
+ *
*/
public UserAdministrationComponent(String aName, boolean aExposeInternals)
throws IOException {
super(aName);
- ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class);
+ ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(
+ UsermgtHibernateMappingFiles.class);
mappingFilesConfig.getSetterConfig().initAllSetters();
addComponent("mappingFiles", new UsermgtHibernateMappingFiles(),
mappingFilesConfig);
addComponent(hibernate);
Component<?> repository = new UserGroupRepositoryComponent(
- "usersgroups");
+ "usersgroups");
addComponent(repository);
Component<?> usermgt = new UserAdministrationLightComponent(
- "usermgtlight");
+ "usermgtlight");
addComponent(usermgt);
addRequiredInterface(new DefaultRequiredInterface("datasource",
- DataSource.class));
+ DataSource.class));
addRequiredInterface(new DefaultRequiredInterface("ormconfig",
- ORMappingConfig.class));
+ ORMappingConfig.class));
if (aExposeInternals) {
addProvidedInterface(TRANSACTION_MGR);
import java.util.HashMap;
import java.util.Map;
-
/**
- * Light version of the user administration component that requires
- * external datasource, and userset and group set components, as well as an
- * external hibernate session factory.
- *
+ * Light version of the user administration component that requires external
+ * datasource, and userset and group set components, as well as an external
+ * hibernate session factory.
+ *
* @author Erik Brakkee
*/
public class UserAdministrationLightComponent extends SpringComponent {
-/**
+ /**
* Creates a new UserAdministrationLightComponent object.
- *
- * @param aName DOCUMENT ME!
+ *
*/
public UserAdministrationLightComponent(String aName) {
super(aName,
createProvided(), createRequired());
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static Map<RequiredInterface, String> createRequired() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
required.put(new DefaultRequiredInterface("userSet", UserSet.class),
return required;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static Map<String, ProvidedInterface> createProvided() {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
provided.put(UserAdministration.class.getName(),
import java.util.Collections;
-
/**
* Hibernate mapping files for user management.
- *
+ *
* @author Erik Brakkee
*/
public class UsermgtHibernateMappingFiles extends HibernateMappingFiles {
-/**
+ /**
* Creates a new UsermgtHibernateMappingFiles object.
*/
public UsermgtHibernateMappingFiles() {
super(new String[] { "hbm/Group.hbm.xml", "hbm/User.hbm.xml" });
}
-/**
+ /**
* Creates a new UsermgtHibernateMappingFiles object.
- *
- * @param aFiles DOCUMENT ME!
+ *
*/
public UsermgtHibernateMappingFiles(String[] aFiles) {
this();
import org.wamblee.usermgt.UserAccessor;
-
/**
* Tests the authorization service.
- *
+ *
* @author Erik Brakkee
*/
public class AuthorizationServiceTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
private AuthorizationRule rule1;
- /**
- * DOCUMENT ME!
- */
private AuthorizationRule rule2;
- /**
- * DOCUMENT ME!
- */
private AuthorizationRule rule3;
- /**
- * DOCUMENT ME!
- */
private AuthorizationService service;
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
protected AuthorizationService getService() {
return service;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see junit.framework.TestCase#setUp()
*/
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
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 = createService();
service.appendRule(rule1);
service.appendRule(rule2);
service.appendRule(rule3);
}
- /**
- * DOCUMENT ME!
- */
protected void resetTestRules() {
((TestAuthorizationRule) rule1).reset();
((TestAuthorizationRule) rule2).reset();
((TestAuthorizationRule) rule3).reset();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
protected UserAccessor createUserAccessor() {
return new TestUserAccessor();
}
/**
* Creates an authorization service with some rules for testing. .
- *
+ *
* @return Authorization service.
*/
protected AuthorizationService createService() {
return service;
}
- /**
- * DOCUMENT ME!
- *
- * @param aResult DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- * @param aPath DOCUMENT ME!
- * @param aOperation DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
protected AuthorizationRule createRule(AuthorizationResult aResult,
- String aGroup, String aPath, Class<?extends Operation> aOperation) {
+ String aGroup, String aPath, Class<? extends Operation> aOperation) {
return new TestAuthorizationRule(aResult, aGroup, aPath, aOperation);
}
- /**
- * DOCUMENT ME!
- *
- * @param aCount DOCUMENT ME!
- * @param aRule DOCUMENT ME!
- */
protected void checkMatchCount(int aCount, AuthorizationRule aRule) {
assertEquals(aCount, ((TestAuthorizationRule) aRule).getMatchCount());
}
- /**
- * DOCUMENT ME!
- *
- * @param aPath DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
protected Object createResource(String aPath) {
return new TestResource(aPath);
}
- /**
- * DOCUMENT ME!
- *
- * @param aCount DOCUMENT ME!
- */
protected void checkRuleCount(int aCount) {
// Empty
}
/**
- * Several checks to verify the outcome of matching against the
- * first rule.
+ * Several checks to verify the outcome of matching against the first rule.
*/
public void testFirstRuleGrants() {
assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"),
- new ReadOperation()));
+ new ReadOperation()));
checkMatchCount(1, rule1);
assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"),
- new WriteOperation()));
+ new WriteOperation()));
checkMatchCount(2, rule1);
assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"),
- new DeleteOperation()));
+ new DeleteOperation()));
checkMatchCount(3, rule1);
assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"),
- new CreateOperation()));
+ new CreateOperation()));
checkMatchCount(4, rule1);
checkMatchCount(0, rule2);
checkMatchCount(0, rule3);
*/
public void testSecondRuleDenies() {
assertFalse(service.isAllowed(createResource("/abc/xyz.jpg"),
- new ReadOperation()));
+ new ReadOperation()));
checkMatchCount(0, rule1);
checkMatchCount(1, rule2);
checkMatchCount(0, rule3);
}
/**
- * Verifies that the third rule is used when appropriate and that
- * it grants access.
+ * Verifies that the third rule is used when appropriate and that it grants
+ * access.
*/
public void testThirdRuleGrants() {
assertTrue(service.isAllowed(createResource("/abc/xyz.jpg"),
- new WriteOperation()));
+ 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()));
+ new WriteOperation()));
service.removeRule(2);
assertFalse(service.isAllowed(createResource("/abc/xyz.jpg"),
- new WriteOperation()));
+ new WriteOperation()));
checkRuleCount(2);
}
public void testInsertRule() {
checkRuleCount(3);
assertFalse(service.isAllowed(createResource("/janse/xyz.jpg"),
- new WriteOperation()));
+ new WriteOperation()));
service.appendRule(createRule(GRANTED, "users", "/janse/",
- WriteOperation.class));
+ WriteOperation.class));
assertTrue(service.isAllowed(createResource("/janse/xyz.jpg"),
- new WriteOperation()));
+ new WriteOperation()));
checkRuleCount(4);
}
*/
public void testNoRulesSupportResource() {
assertFalse(service.isAllowed(createResource("/xyxyxyxy"),
- new ReadOperation()));
+ new ReadOperation()));
checkMatchCount(0, rule1);
checkMatchCount(0, rule2);
checkMatchCount(0, rule3);
import junit.framework.TestCase;
-
/**
* Test of the operation registry.
- *
+ *
* @author Erik Brakkee
*/
public class DefaultOperationRegistryTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
private OperationRegistry registry;
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see junit.framework.TestCase#setUp()
*/
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
registry = new DefaultOperationRegistry(new Operation[] {
- new AllOperation(), new ReadOperation(),
- new WriteOperation(), new DeleteOperation(),
- new CreateOperation()
- });
+ new AllOperation(), new ReadOperation(), new WriteOperation(),
+ new DeleteOperation(), new CreateOperation() });
}
/**
* Verifies that encoding of operations into a string works.
*/
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() }));
}
/**
}
/**
- * Verifies that an IllegalArgumentException occurs when attempting
- * to decode an operation that is not known.
+ * Verifies that an IllegalArgumentException occurs when attempting to
+ * decode an operation that is not known.
*/
public void testDecodeUnknownOperation() {
try {
import junit.framework.TestCase;
-
/**
* Test for regular expression matching.
- *
+ *
* @author Erik Brakkee
*/
public class RegexpPathConditionTest extends TestCase {
import junit.framework.TestCase;
-
/**
* Tests for StartsWithPathCondition.
- *
+ *
* @author Erik Brakkee
*/
public class StartsWithPathConditionTest extends TestCase {
import org.wamblee.usermgt.User;
-
/**
* Test authorization rule that also counts the number of times the rule
* matches.
- *
+ *
* @author Erik Brakkee
*/
public class TestAuthorizationRule extends UrlAuthorizationRule {
*/
private int matches = 0;
-/**
+ /**
* Creates a new TestAuthorizationRule object.
- *
- * @param aResult DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- * @param aPath DOCUMENT ME!
- * @param aOperation DOCUMENT ME!
+ *
*/
public TestAuthorizationRule(AuthorizationResult aResult, String aGroup,
- String aPath, Class<?extends Operation> aOperation) {
+ String aPath, Class<? extends Operation> aOperation) {
super(aResult, new GroupUserCondition(aGroup),
new StartsWithPathCondition(aPath), TestResource.class,
new IsaOperationCondition(aOperation));
}
-/**
+ /**
* Creates a new TestAuthorizationRule object.
*/
protected TestAuthorizationRule() {
super();
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.UrlAuthorizationRule#getPath(java.lang.Object)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aResource DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.UrlAuthorizationRule#getPath(java.
+ * lang.Object)
*/
@Override
protected String getResourcePath(Object aResource) {
return ((TestResource) aResource).getPath();
}
- /* (non-Javadoc)
- * @see org.wamblee.security.authorization.UrlAuthorizationRule#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation, org.wamblee.usermgt.UserAccessor)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aResource DOCUMENT ME!
- * @param anOperation DOCUMENT ME!
- * @param aUser DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.security.authorization.UrlAuthorizationRule#isAllowed(java
+ * .lang.Object, org.wamblee.security.authorization.Operation,
+ * org.wamblee.usermgt.UserAccessor)
*/
@Override
public AuthorizationResult isAllowed(Object aResource,
Operation anOperation, User aUser) {
AuthorizationResult result = super.isAllowed(aResource, anOperation,
- aUser);
+ aUser);
if (result.equals(GRANTED) || result.equals(DENIED)) {
matches++;
return result;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public int getMatchCount() {
return matches;
}
- /**
- * DOCUMENT ME!
- */
public void reset() {
matches = 0;
}
/**
* A test resource for authorization.
- *
+ *
* @author Erik Brakkee
*/
public class TestResource {
- /**
- * DOCUMENT ME!
- */
private String path;
-/**
+ /**
* Creates a new TestResource object.
- *
- * @param aPath DOCUMENT ME!
+ *
*/
public TestResource(String aPath) {
path = aPath;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String getPath() {
return path;
}
import org.wamblee.usermgt.UserMgtException;
import org.wamblee.usermgt.UserMgtException.Reason;
-
/**
* User access that always returns a user that belongs to a fixed group.
- *
+ *
* @author Erik Brakkee
*/
public class TestUserAccessor implements UserAccessor {
- /**
- * DOCUMENT ME!
- */
private static final String USER = "erik";
- /**
- * DOCUMENT ME!
- */
private static final String PASSWORD = "abc123";
- /**
- * DOCUMENT ME!
- */
private static final String GROUP = "users";
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAccessor#getCurrentUser()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws RuntimeException DOCUMENT ME!
- */
public User getCurrentUser() {
- UserAdministration admin = new UserAdministrationImpl(new InMemoryUserSet(
- new RegexpNameValidator(
- RegexpNameValidator.PASSWORD_PATTERN,
- Reason.INVALID_PASSWORD,
- "Password must contain at least 6 characters"),
- new Md5HexMessageDigester()), new InMemoryGroupSet(),
- new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
- Reason.INVALID_USERNAME, "Invalid user"),
- new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
- Reason.INVALID_GROUPNAME, "Invalid group"));
+ UserAdministration admin = new UserAdministrationImpl(
+ new InMemoryUserSet(new RegexpNameValidator(
+ RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD,
+ "Password must contain at least 6 characters"),
+ new Md5HexMessageDigester()), new InMemoryGroupSet(),
+ new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
+ Reason.INVALID_USERNAME, "Invalid user"),
+ new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
+ Reason.INVALID_GROUPNAME, "Invalid group"));
try {
Group group = admin.createGroup(GROUP);
import org.wamblee.usermgt.User;
-
/**
- * Tests for the {@link
- * org.wamblee.security.authorization.UrlAuthorizationRule}.
- *
+ * Tests for the {@link org.wamblee.security.authorization.UrlAuthorizationRule}
+ * .
+ *
* @author Erik Brakkee
*/
public class UrlAuthorizationRuleTest extends TestCase {
/**
* Constructs the rule with a result of UNDECIDED. Verifies that an
- * IllegalArgumentException is thrown.
+ * IllegalArgumentException is thrown.
*/
public void testConstructWithUndecidedResult() {
try {
ReadOperation.class);
fail();
} catch (IllegalArgumentException e) {
- // ok
+ // ok
}
}
/**
- * Constructs the rule with a result of UNSUPPORTED_RESOURCE.
- * Verifies that an IllegalArgumentException is thrown.
+ * Constructs the rule with a result of UNSUPPORTED_RESOURCE. Verifies that
+ * an IllegalArgumentException is thrown.
*/
public void testConstructWithUnsupportedResult() {
try {
ReadOperation.class);
fail();
} catch (IllegalArgumentException e) {
- // ok
+ // ok
}
}
/**
- * Constructs the authorization rule and applies it to an
- * unsupported object type. Verifies that the result is
- * UNSUPPORTED_RESOURCE.
+ * Constructs the authorization rule and applies it to an unsupported object
+ * type. Verifies that the result is UNSUPPORTED_RESOURCE.
*/
public void testUnsupportedObject() {
AuthorizationRule rule = new TestAuthorizationRule(GRANTED, "users",
- "/path", ReadOperation.class);
- assertEquals(UNSUPPORTED_RESOURCE,
- rule.isAllowed("hello", new ReadOperation(),
- new TestUserAccessor().getCurrentUser()));
+ "/path", ReadOperation.class);
+ assertEquals(UNSUPPORTED_RESOURCE, rule.isAllowed("hello",
+ new ReadOperation(), new TestUserAccessor().getCurrentUser()));
}
- /**
- * DOCUMENT ME!
- */
public void testMatchingScenarios() {
AuthorizationRule rule = new TestAuthorizationRule(GRANTED, "users",
- "/path/", ReadOperation.class);
- User user = new TestUserAccessor().getCurrentUser();
+ "/path/", ReadOperation.class);
+ User user = new TestUserAccessor().getCurrentUser();
// everything matches
- assertEquals(GRANTED,
- rule.isAllowed(new TestResource("/path/a"), new ReadOperation(),
- user));
- assertEquals(GRANTED,
- rule.isAllowed(new TestResource("/path/"), new ReadOperation(), user));
+ assertEquals(GRANTED, rule.isAllowed(new TestResource("/path/a"),
+ new ReadOperation(), user));
+ assertEquals(GRANTED, rule.isAllowed(new TestResource("/path/"),
+ new ReadOperation(), user));
- // path does not match.
- assertEquals(UNDECIDED,
- rule.isAllowed(new TestResource("/path"), new ReadOperation(), user));
+ // path does not match.
+ assertEquals(UNDECIDED, rule.isAllowed(new TestResource("/path"),
+ new ReadOperation(), user));
- // operation does not match.
- assertEquals(UNDECIDED,
- rule.isAllowed(new TestResource("/path/"), new WriteOperation(),
- user));
+ // operation does not match.
+ assertEquals(UNDECIDED, rule.isAllowed(new TestResource("/path/"),
+ new WriteOperation(), user));
- // group does not match.
+ // group does not match.
AuthorizationRule rule2 = new TestAuthorizationRule(GRANTED, "users2",
- "/path/", ReadOperation.class);
- assertEquals(UNDECIDED,
- rule2.isAllowed(new TestResource("/path/a"), new ReadOperation(),
- user));
+ "/path/", ReadOperation.class);
+ assertEquals(UNDECIDED, rule2.isAllowed(new TestResource("/path/a"),
+ new ReadOperation(), user));
}
}
import java.sql.SQLException;
-
/**
* Unit test for the persistent authorization service.
- *
+ *
* @author Erik Brakkee
*/
-public class PersistentAuthorizationServiceTest extends AuthorizationServiceTest {
- /**
- * DOCUMENT ME!
- */
- private static final Logger LOGGER = Logger.getLogger(PersistentAuthorizationServiceTest.class);
+public class PersistentAuthorizationServiceTest extends
+ AuthorizationServiceTest {
+ private static final Logger LOGGER = Logger
+ .getLogger(PersistentAuthorizationServiceTest.class);
- /**
- * DOCUMENT ME!
- */
private static final String SERVICE_TABLE = "AUTHORIZATION_SERVICE";
- /**
- * DOCUMENT ME!
- */
private static final String RULES_TABLE = "AUTHORIZATION_RULES";
- /**
- * DOCUMENT ME!
- */
private static final String SERVICE_RULES_TABLE = "AUTHORIZATION_SERVICE_RULES";
- /**
- * DOCUMENT ME!
- */
private static final String OPERATIONCOND_TABLE = "OPERATION_CONDITIONS";
- /**
- * DOCUMENT ME!
- */
private static final String PATHCOND_TABLE = "PATH_CONDITIONS";
- /**
- * DOCUMENT ME!
- */
private static final String USERCOND_TABLE = "USER_CONDITIONS";
- /**
- * DOCUMENT ME!
- */
private DefaultContainer container;
- /**
- * DOCUMENT ME!
- */
private Scope scope;
- /**
- * DOCUMENT ME!
- */
private DatabaseTesterComponent databaseTester;
- /**
- * DOCUMENT ME!
- */
private UserAccessor userAccessor;
- /**
- * DOCUMENT ME!
- */
private HibernateTemplate hibernateTemplate;
- /**
- * DOCUMENT ME!
- */
private AuthorizationService authorizationService;
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
container = new DefaultContainer("top");
DatabaseComponentFactory.addDatabaseConfig(container);
container.addComponent(new DatasourceComponent("datasource"));
- ClassConfiguration useraccessorConfig = new ClassConfiguration(TestUserAccessor.class);
+ ClassConfiguration useraccessorConfig = new ClassConfiguration(
+ TestUserAccessor.class);
useraccessorConfig.getObjectConfig().getSetterConfig().initAllSetters();
container.addComponent("userAccessor", useraccessorConfig);
- container.addComponent(new AuthorizationComponent("authorization", true));
+ container
+ .addComponent(new AuthorizationComponent("authorization", true));
- ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class);
+ ClassConfiguration dbtesterConfig = new ClassConfiguration(
+ DatabaseTesterComponent.class);
dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
container.addComponent("databaseTester", dbtesterConfig);
- ObjectConfiguration config = new ObjectConfiguration(PersistentAuthorizationServiceTest.class);
- config.getSetterConfig().clear().add("setUserAccessor")
- .add("setDatabaseTester").add("setHibernateTemplate")
- .add("setAuthorizationService");
+ ObjectConfiguration config = new ObjectConfiguration(
+ PersistentAuthorizationServiceTest.class);
+ config.getSetterConfig().clear().add("setUserAccessor").add(
+ "setDatabaseTester").add("setHibernateTemplate").add(
+ "setAuthorizationService");
container.addComponent("testcase", this, config);
scope = container.start();
super.setUp();
}
- /**
- * DOCUMENT ME!
- *
- * @param aDatabaseTester DOCUMENT ME!
- */
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
databaseTester = aDatabaseTester;
}
- /**
- * DOCUMENT ME!
- *
- * @param aUserAccessor DOCUMENT ME!
- */
public void setUserAccessor(UserAccessor aUserAccessor) {
userAccessor = aUserAccessor;
}
- /**
- * DOCUMENT ME!
- *
- * @param aHibernateTemplate DOCUMENT ME!
- */
public void setHibernateTemplate(HibernateTemplate aHibernateTemplate) {
hibernateTemplate = aHibernateTemplate;
}
- /**
- * DOCUMENT ME!
- *
- * @param aAuthorizationService DOCUMENT ME!
- */
public void setAuthorizationService(
AuthorizationService aAuthorizationService) {
authorizationService = aAuthorizationService;
/*
* (non-Javadoc)
- *
+ *
* @see
* org.wamblee.security.authorization.AuthorizationServiceTest#createService
* ()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected AuthorizationService createService() {
- PersistentAuthorizationService service = new PersistentAuthorizationService("DEFAULT",
- hibernateTemplate, createUserAccessor(), 10000);
+ PersistentAuthorizationService service = new PersistentAuthorizationService(
+ "DEFAULT", hibernateTemplate, createUserAccessor(), 10000);
return service;
}
/*
* (non-Javadoc)
- *
+ *
* @see
* org.wamblee.security.authorization.AuthorizationServiceTest#checkRuleCount
* (int)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aCount DOCUMENT ME!
- *
- * @throws RuntimeException DOCUMENT ME!
- */
@Override
protected void checkRuleCount(int aCount) {
try {
assertEquals(1, databaseTester.getTableSize(SERVICE_TABLE));
assertEquals(aCount, databaseTester.getTableSize(RULES_TABLE));
- assertEquals(aCount,
- databaseTester.getTableSize(SERVICE_RULES_TABLE));
+ assertEquals(aCount, databaseTester
+ .getTableSize(SERVICE_RULES_TABLE));
assertEquals(aCount, databaseTester.getTableSize(USERCOND_TABLE));
assertEquals(aCount, databaseTester.getTableSize(PATHCOND_TABLE));
- assertEquals(aCount,
- databaseTester.getTableSize(OPERATIONCOND_TABLE));
+ assertEquals(aCount, databaseTester
+ .getTableSize(OPERATIONCOND_TABLE));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
- /**
- * DOCUMENT ME!
- */
public void testSchemaExport() {
Configuration config = new Configuration();
config.addResource(mappingFile);
}
- config.setProperty("hibernate.dialect",
- MySQL5InnoDBDialect.class.getName());
+ config.setProperty("hibernate.dialect", MySQL5InnoDBDialect.class
+ .getName());
SchemaExport exporter = new SchemaExport(config);
exporter.setOutputFile("target/mysql5.schema.sql");
exporter.create(true, false);
}
- /**
- * DOCUMENT ME!
- */
public void testPerformance() {
PersistentAuthorizationService service = (PersistentAuthorizationService) getService();
- int n = 1000;
- long time = System.currentTimeMillis();
+ int n = 1000;
+ long time = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
testFirstRuleGrants();
testNoRulesSupportResource();
}
- LOGGER.info("Executed " + (4 * n) + " authorization checks in "
- + ((float) (System.currentTimeMillis() - time) / (float) 1000)
- + " seconds.");
+ LOGGER.info("Executed " + (4 * n) + " authorization checks in " +
+ ((float) (System.currentTimeMillis() - time) / (float) 1000) +
+ " seconds.");
}
}
import junit.framework.TestCase;
-
/**
* Tests for the message digester.
- *
+ *
* @author Erik Brakkee
*/
public class MessageDigesterTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
public void testMd5HexEncoding() {
assertEquals("e99a18c428cb38d5f260853678922e03",
new Md5HexMessageDigester().hash("abc123"));
import java.util.Set;
-
/**
* Tests the inmemory group set. Intended to be subclassed for other
* implementations of group set.
*/
public class InMemoryGroupSetTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
protected GroupSet groups;
/**
* This method must be overriden in subclasses.
- *
+ *
* @return New group set object.
*/
protected GroupSet createGroupSet() {
return new InMemoryGroupSet();
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.test.SpringTestCase#setUp()
*/
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
super.setUp();
/**
* Additional check to be implemented by a subclass.
- *
- * @param aGroup Group to check for existence.
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @param aGroup
+ * Group to check for existence.
+ *
*/
protected void checkGroupExists(String aGroup) throws SQLException {
// Empty
/**
* Additional check to be implemented by a subclass.
- *
- * @param aGroup Group to check for non-existence.
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @param aGroup
+ * Group to check for non-existence.
+ *
*/
protected void checkGroupNotExists(String aGroup) throws SQLException {
// Empty
/**
* Additional check to be implemented by a subclass.
- *
- * @param aSize Expected number of groups.
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @param aSize
+ * Expected number of groups.
+ *
*/
protected void checkGroupCount(int aSize) throws SQLException {
assertEquals(aSize, groups.size());
}
/**
- * Adds a group and verifies that the group is added using find(),
- * list(), and contains().
- *
- * @throws SQLException DOCUMENT ME!
+ * Adds a group and verifies that the group is added using find(), list(),
+ * and contains().
+ *
*/
public void testAdd() throws SQLException {
Group group = new Group("group1");
}
/**
- * Tries to find a non-existing group. Verifies that null is
- * returned.
- *
- * @throws SQLException DOCUMENT ME!
+ * Tries to find a non-existing group. Verifies that null is returned.
+ *
*/
public void testFindUnknownGroup() throws SQLException {
Group group1 = new Group("group1");
}
/**
- * Adds duplicate group. Verifies that the existing group is left
- * untouched.
- *
- * @throws SQLException DOCUMENT ME!
+ * Adds duplicate group. Verifies that the existing group is left untouched.
+ *
*/
public void testAddDuplicateGroup() throws SQLException {
Group group1 = new Group("group1");
}
/**
- * Removes a group. Verifies that the group is removed and the
- * return value is true.
- *
- * @throws SQLException DOCUMENT ME!
+ * Removes a group. Verifies that the group is removed and the return value
+ * is true.
+ *
*/
public void testRemoveGroup() throws SQLException {
Group group1 = new Group("group1");
}
/**
- * Removes a non-existing group. Verifies that no groups are
- * removed an that the return value is true.
- *
- * @throws SQLException DOCUMENT ME!
+ * Removes a non-existing group. Verifies that no groups are removed an that
+ * the return value is true.
+ *
*/
public void testRemoveNonExistingGroup() throws SQLException {
Group group1 = new Group("group1");
}
/**
- * Adds a number of groups to the set and verifies that list()
- * returns them all.
- *
- * @throws SQLException DOCUMENT ME!
+ * Adds a number of groups to the set and verifies that list() returns them
+ * all.
+ *
*/
public void testList() throws SQLException {
Group group1 = new Group("group1");
import java.util.Set;
-
/**
* Tests the inmemory user set. Intended to be subclassed for other
* implementations of user set.
*/
public class InMemoryUserSetTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
protected static final String PASSWORD = "abc123";
- /**
- * DOCUMENT ME!
- */
private UserSet users;
- /**
- * DOCUMENT ME!
- */
private GroupSet groups;
- /**
- * DOCUMENT ME!
- */
private Group group;
/**
* This method must be overriden in subclasses.
- *
+ *
* @return New user set object.
*/
protected UserSet createUserSet() {
return new InMemoryUserSet(new RegexpNameValidator(
- RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD,
- "Password must contain at least 6 characters"),
+ RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD,
+ "Password must contain at least 6 characters"),
new Md5HexMessageDigester());
}
/**
* This method must be overriden in subclasses.
- *
+ *
* @return New group set object.
*/
protected GroupSet createGroupSet() {
return new InMemoryGroupSet();
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.test.SpringTestCase#setUp()
*/
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
super.setUp();
- users = createUserSet();
- groups = createGroupSet();
- group = new Group("group0");
+ users = createUserSet();
+ groups = createGroupSet();
+ group = new Group("group0");
groups.add(group);
checkUserCount(0);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
protected UserSet getUsers() {
return users;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
protected GroupSet getGroups() {
return groups;
}
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
protected Group createGroup(String aName) {
return new Group(aName);
}
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- * @param aPassword DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
protected User createUser(String aName, String aPassword, Group aGroup)
throws UserMgtException {
return UsermgtTestUtils.createUser(aName, aPassword, aGroup);
}
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
protected void addUserToGroup(User aUser, Group aGroup)
throws UserMgtException {
aUser.addGroup(aGroup);
}
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
protected void removeUserFromGroup(User aUser, Group aGroup)
throws UserMgtException {
aUser.removeGroup(aGroup);
/**
* Additional check to be implemented by a subclass.
- *
- * @param aUser User to check for existence.
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @param aUser
+ * User to check for existence.
+ *
*/
protected void checkUserExists(String aUser) throws SQLException {
// Empty
/**
* Additional check to be implemented by a subclass.
- *
- * @param aUser User to check for non-existence.
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @param aUser
+ * User to check for non-existence.
+ *
*/
protected void checkUserNotExists(String aUser) throws SQLException {
// Empty
/**
* Additional check to be implemented by a subclass.
- *
- * @param aSize Expected number of users.
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @param aSize
+ * Expected number of users.
+ *
*/
protected void checkUserCount(int aSize) throws SQLException {
assertEquals(aSize, users.size());
/**
* Additional check to be implemented by a subclass.
- *
- * @param aUser User to check for existence.
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @param aUser
+ * User to check for existence.
+ *
*/
protected void checkGroupExists(String aUser) throws SQLException {
// Empty
/**
* Additional check to be implemented by a subclass.
- *
- * @param aUser User to check for non-existence.
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @param aUser
+ * User to check for non-existence.
+ *
*/
protected void checkGroupNotExists(String aUser) throws SQLException {
// Empty
/**
* Additional check to be implemented by a subclass.
- *
- * @param aSize Expected number of users.
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @param aSize
+ * Expected number of users.
+ *
*/
protected void checkGroupCount(int aSize) throws SQLException {
// Empty
}
/**
- * Adds a user and verifies that the user is added using find(),
- * list(), and contains().
- *
- * @throws SQLException DOCUMENT ME!
- * @throws UserMgtException DOCUMENT ME!
+ * Adds a user and verifies that the user is added using find(), list(), and
+ * contains().
+ *
*/
public void testAdd() throws SQLException, UserMgtException {
User user = createUser("user1", PASSWORD, group);
}
/**
- * Tries to find a non-existing user. Verifies that null is
- * returned.
- *
- * @throws SQLException DOCUMENT ME!
- * @throws UserMgtException DOCUMENT ME!
+ * Tries to find a non-existing user. Verifies that null is returned.
+ *
*/
public void testFindUnknownUser() throws SQLException, UserMgtException {
User user1 = createUser("user1", PASSWORD, group);
}
/**
- * Adds duplicate user. Verifies that the existing user is left
- * untouched.
- *
- * @throws SQLException DOCUMENT ME!
- * @throws UserMgtException DOCUMENT ME!
+ * Adds duplicate user. Verifies that the existing user is left untouched.
+ *
*/
public void testAddDuplicateUser() throws SQLException, UserMgtException {
User user1 = createUser("user1", PASSWORD, group);
}
/**
- * Removes a user. Verifies that the user is removed and the
- * return value is true.
- *
- * @throws SQLException DOCUMENT ME!
- * @throws UserMgtException DOCUMENT ME!
+ * Removes a user. Verifies that the user is removed and the return value is
+ * true.
+ *
*/
public void testRemoveUser() throws SQLException, UserMgtException {
User user1 = createUser("user1", PASSWORD, group);
}
/**
- * Removes a non-existing user. Verifies that no users are removed
- * an that the return value is true.
- *
- * @throws SQLException DOCUMENT ME!
- * @throws UserMgtException DOCUMENT ME!
+ * Removes a non-existing user. Verifies that no users are removed an that
+ * the return value is true.
+ *
*/
- public void testRemoveNonExistingUser()
- throws SQLException, UserMgtException {
+ public void testRemoveNonExistingUser() throws SQLException,
+ UserMgtException {
User user1 = createUser("user1", PASSWORD, group);
users.add(user1);
checkUserCount(1);
}
/**
- * Adds a number of users to the set and verifies that list()
- * returns them all.
- *
- * @throws SQLException DOCUMENT ME!
- * @throws UserMgtException DOCUMENT ME!
+ * Adds a number of users to the set and verifies that list() returns them
+ * all.
+ *
*/
public void testList() throws SQLException, UserMgtException {
User user1 = createUser("user1", PASSWORD, group);
}
/**
- * Adds several users to different groups and verifies that the
- * correct users are returned when looking for users in different groups.
- *
+ * Adds several users to different groups and verifies that the correct
+ * users are returned when looking for users in different groups.
+ *
* @throws SQLException
- * @throws UserMgtException DOCUMENT ME!
*/
public void testListByGroup() throws SQLException, UserMgtException {
Group group1 = new Group("group1");
groups.add(group2);
groups.add(group3);
- // user1 user2 user3
- // group1 y
- // group2 y y
- // group3 y y y
+ // user1 user2 user3
+ // group1 y
+ // group2 y y
+ // group3 y y y
User user1 = createUser("user1", PASSWORD, group1);
user1.addGroup(group2);
user1.addGroup(group3);
checkGroupExists(group3.getName());
checkUserCount(3);
- checkGroupCount(3 + 1); // also count the group that was created in the setUp().
+ checkGroupCount(3 + 1); // also count the group that was created in the
+ // setUp().
Set<User> list = users.list(group1);
assertTrue(list.contains(user1));
import java.util.Set;
-
/**
* Test of user administration implementation.
- *
+ *
* @author Erik Brakkee
*/
public class UserAdministrationImplTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
- private static final Logger LOGGER = Logger.getLogger(UserAdministrationImplTest.class);
+ private static final Logger LOGGER = Logger
+ .getLogger(UserAdministrationImplTest.class);
- /**
- * DOCUMENT ME!
- */
private static final String USER1 = "piet";
- /**
- * DOCUMENT ME!
- */
private static final String PASS1 = "passpiet";
- /**
- * DOCUMENT ME!
- */
private static final String USER2 = "kees";
- /**
- * DOCUMENT ME!
- */
private static final String PASS2 = "passkees";
- /**
- * DOCUMENT ME!
- */
private static final String GROUP1 = "cyclists";
- /**
- * DOCUMENT ME!
- */
private static final String GROUP2 = "runners";
- /**
- * DOCUMENT ME!
- */
private UserAdministration admin;
/*
* (non-Javadoc)
- *
+ *
* @see junit.framework.TestCase#setUp()
*/
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
super.setUp();
admin = createAdmin();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
protected UserAdministration createAdmin() {
- UserSet users = new InMemoryUserSet(new RegexpNameValidator(
- RegexpNameValidator.PASSWORD_PATTERN,
- Reason.INVALID_PASSWORD,
- "Password must contain at least 6 characters"),
- new Md5HexMessageDigester());
+ UserSet users = new InMemoryUserSet(new RegexpNameValidator(
+ RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD,
+ "Password must contain at least 6 characters"),
+ new Md5HexMessageDigester());
GroupSet groups = new InMemoryGroupSet();
return new UserAdministrationImpl(users, groups,
Reason.INVALID_GROUPNAME, "Invalid group"));
}
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- * @param aPassword DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
protected User createUser(String aName, String aPassword, Group aGroup)
throws UserMgtException {
return UsermgtTestUtils.createUser(aName, aPassword, aGroup);
}
/**
- * Creates a new group. Verifies the group is created correctly and
- * that the user is added.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Creates a new group. Verifies the group is created correctly and that the
+ * user is added.
+ *
*/
public void testCreateGroup() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
assertTrue(groups.contains(group));
}
- /**
- * DOCUMENT ME!
- *
- * @param aUsername DOCUMENT ME!
- */
private void createInvalidGroup(String aUsername) {
try {
admin.createGroup(aUsername);
fail();
} catch (UserMgtException e) {
- assertEquals(UserMgtException.Reason.INVALID_GROUPNAME,
- e.getReason());
+ assertEquals(UserMgtException.Reason.INVALID_GROUPNAME, e
+ .getReason());
assertEquals(0, admin.getGroupCount());
}
}
/**
- * Creates a new group with an invalid name. Verifies that the
- * appropriate exception is thrown.
- *
+ * Creates a new group with an invalid name. Verifies that the appropriate
+ * exception is thrown.
+ *
* @throws UserMgtException
*/
public void testCreateInvalidGroupName() throws UserMgtException {
}
/**
- * Creates a new group which conflicts with an existing one.
- * Verifies that the UserMgtException is thrown and that no group is
- * added.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Creates a new group which conflicts with an existing one. Verifies that
+ * the UserMgtException is thrown and that no group is added.
+ *
*/
public void testCreateDuplicateGroup() throws UserMgtException {
admin.createGroup(GROUP1);
}
/**
- * Creates a new user. Verifies the user is created correctly and
- * that the user is added.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Creates a new user. Verifies the user is created correctly and that the
+ * user is added.
+ *
*/
public void testCreateUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ User user = admin.createUser(USER1, PASS1, group);
assertNotNull(user);
assertEquals(USER1, user.getName());
user.checkPassword(PASS1);
assertTrue(users.contains(user));
}
- /**
- * DOCUMENT ME!
- *
- * @param aUsername DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- */
private void createInvalidUser(String aUsername, Group aGroup) {
try {
admin.createUser(aUsername, "pass", aGroup);
fail();
} catch (UserMgtException e) {
- assertEquals(UserMgtException.Reason.INVALID_USERNAME, e.getReason());
+ assertEquals(UserMgtException.Reason.INVALID_USERNAME, e
+ .getReason());
assertEquals(0, admin.getUserCount());
}
}
/**
- * Constructs users with invalid names. Verifies that the
- * appropriate exception is thrown.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Constructs users with invalid names. Verifies that the appropriate
+ * exception is thrown.
+ *
*/
public void testCreateInvalidUserName() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
}
/**
- * Creates a new user which conflicts with an existing one.
- * Verifies that the UserMgtException is thrown and that no user is added.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Creates a new user which conflicts with an existing one. Verifies that
+ * the UserMgtException is thrown and that no user is added.
+ *
*/
public void testCreateDuplicateUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
}
/**
- * Gets a known user by name. Verifies the correct user is
- * obtained. Verifies that null is returned when trying to obtain an
- * unknown user.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Gets a known user by name. Verifies the correct user is obtained.
+ * Verifies that null is returned when trying to obtain an unknown user.
+ *
*/
public void testGetUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
- User user2 = admin.getUser(USER1);
+ User user = admin.createUser(USER1, PASS1, group);
+ User user2 = admin.getUser(USER1);
assertTrue(user.equals(user2));
assertNull(admin.getUser(USER2));
}
/**
- * Gets a known group by name. Verifies the correct group is
- * obtained. Verifies that null is returned when the group is not known.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Gets a known group by name. Verifies the correct group is obtained.
+ * Verifies that null is returned when the group is not known.
+ *
*/
public void testGetGroup() throws UserMgtException {
- Group group = admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
Group group2 = admin.getGroup(GROUP1);
assertTrue(group.equals(group2));
assertNull(admin.getGroup(GROUP2));
}
/**
- * Adds a user to a group. Verifies that the user is added using
- * several API calls. Verifies that an exception occurs if the user is not
- * already part of the group.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Adds a user to a group. Verifies that the user is added using several API
+ * calls. Verifies that an exception occurs if the user is not already part
+ * of the group.
+ *
*/
public void testAddUserToGroup() 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 = admin.createGroup(GROUP2);
assertTrue(user.isInGroup(group));
assertFalse(user.isInGroup(group2));
try {
admin.addUserToGroup(user, group);
} catch (UserMgtException e) {
- assertEquals(UserMgtException.Reason.USER_ALREADY_IN_GROUP,
- e.getReason());
+ assertEquals(UserMgtException.Reason.USER_ALREADY_IN_GROUP, e
+ .getReason());
return;
}
}
/**
- * Adds a user to a group where the user does not exist. Verifies
- * that an exception occurs.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Adds a user to a group where the user does not exist. Verifies that an
+ * exception occurs.
+ *
*/
public void testAddUserToGroupUnknownUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = createUser(USER1, PASS1, group);
+ User user = createUser(USER1, PASS1, group);
try {
admin.addUserToGroup(user, group);
}
/**
- * Adds a user to a group where the user does not exist. Verifies
- * that an exception occurs.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Adds a user to a group where the user does not exist. Verifies that an
+ * exception occurs.
+ *
*/
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 {
}
/**
- * Removes a user from a group. Verifies that the user is removed
- * from the group using several API calls. Verifies that an exception
- * occurs if the user not part of the group or if the user is only part of
- * one group.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Removes a user from a group. Verifies that the user is removed from the
+ * group using several API calls. Verifies that an exception occurs if the
+ * 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);
+ User user = admin.createUser(USER1, PASS1, group);
Group group2 = admin.createGroup(GROUP2);
admin.addUserToGroup(user, group2);
}
/**
- * Removes a user from a group where the user is not known.
- * Verifies that an exception is thrown.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Removes a user from a group where the user is not known. Verifies that an
+ * exception is thrown.
+ *
*/
public void testRemoveUserFromGroupUnknownUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = createUser(USER1, GROUP1, group);
+ User user = createUser(USER1, GROUP1, group);
try {
admin.removeUserFromGroup(user, group);
}
/**
- * Removes a user from a group where the group is not known.
- * Verifies that an exception is thrown.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Removes a user from a group where the group is not known. Verifies that
+ * an exception is thrown.
+ *
*/
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 {
}
/**
- * Removes a user from a group where the user is only part of one
- * group. Verifies that an exception is thrown.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Removes a user from a group where the user is only part of one group.
+ * Verifies that an exception is thrown.
+ *
*/
public void testRemoveUserFromGroupOnlyGroup() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ User user = admin.createUser(USER1, PASS1, group);
try {
admin.removeUserFromGroup(user, group);
} catch (UserMgtException e) {
- assertEquals(UserMgtException.Reason.USER_MUST_BE_IN_A_GROUP,
- e.getReason());
+ assertEquals(UserMgtException.Reason.USER_MUST_BE_IN_A_GROUP, e
+ .getReason());
}
}
/**
- * Gets the list of users and groups. Verifies that the correct
- * suers and groups are returned. Verifies also that the relations from
- * user to group are correct.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Gets the list of users and groups. Verifies that the correct suers and
+ * groups are returned. Verifies also that the relations from user to group
+ * are correct.
+ *
*/
public void testGetUsersAndGroups() throws UserMgtException {
Group group1 = admin.createGroup(GROUP1);
Group group2 = admin.createGroup(GROUP2);
- User user1 = admin.createUser(USER1, PASS1, group1);
+ User user1 = admin.createUser(USER1, PASS1, group1);
admin.addUserToGroup(user1, group2);
- User user2 = admin.createUser(USER2, PASS2, group2);
+ User user2 = admin.createUser(USER2, PASS2, group2);
Set<User> users = admin.getUsers();
assertEquals(2, users.size());
* Renames a user. Verifies that the user is renamed. Verifies that
* exceptions are thrown when an attempt is made to rename the user to
* itself or to another existing user, or when the group does not exist.
- *
- * @throws UserMgtException DOCUMENT ME!
+ *
*/
public void testRenameUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user1 = admin.createUser(USER1, PASS1, group);
+ User user1 = admin.createUser(USER1, PASS1, group);
admin.renameUser(user1, USER2);
assertEquals(USER2, user1.getName());
assertEquals(user1, admin.getUser(USER2));
try {
admin.renameUser(user1, user1.getName());
} catch (UserMgtException e2) {
- assertEquals(UserMgtException.Reason.TRIVIAL_RENAME,
- e2.getReason());
+ assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2
+ .getReason());
return;
}
}
/**
- * Renames a user to a user with an invalid username. Verifies that
- * the appropriate exception is thrown.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Renames a user to a user with an invalid username. Verifies that the
+ * appropriate exception is thrown.
+ *
*/
public void testRenameUserInvalidUsername() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user1 = admin.createUser(USER1, PASS1, group);
+ User user1 = admin.createUser(USER1, PASS1, group);
try {
admin.renameUser(user1, USER2);
}
/**
- * Renames a group. Verifies that the group is renamed. Verifies
- * that exceptions are thrown when an attempt is made to rename the group
- * to itself or to another existing group or when the group does not
- * exist.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Renames a group. Verifies that the group is renamed. Verifies that
+ * exceptions are thrown when an attempt is made to rename the group to
+ * itself or to another existing group or when the group does not exist.
+ *
*/
public void testRenameGroup() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
try {
admin.renameGroup(group, group.getName());
} catch (UserMgtException e2) {
- assertEquals(UserMgtException.Reason.TRIVIAL_RENAME,
- e2.getReason());
+ assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2
+ .getReason());
return;
}
}
/**
- * Renames a group to a group with an invalid name. Verifies that
- * the appropriate exception is thrown.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Renames a group to a group with an invalid name. Verifies that the
+ * appropriate exception is thrown.
+ *
*/
public void testRenameGroupInvalidGroupname() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
}
/**
- * Removes a user. Verifies that the user is removed. Verifies that
- * the an exception is thrown when the user does not exist.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Removes a user. Verifies that the user is removed. Verifies that the an
+ * exception is thrown when the user does not exist.
+ *
*/
public void testRemoveUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ User user = admin.createUser(USER1, PASS1, group);
assertEquals(1, admin.getUserCount());
admin.removeUser(user);
}
/**
- * Removes a group. Verifies that the group is removed. Verifies
- * that the an exception is thrown when the group does not exist or if
- * there are still users in the group.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Removes a group. Verifies that the group is removed. Verifies that the an
+ * exception is thrown when the group does not exist or if there are still
+ * users in the group.
+ *
*/
public void testRemoveGroup() throws UserMgtException {
Group group1 = admin.createGroup(GROUP1);
try {
admin.removeGroup(group1);
} catch (UserMgtException e) {
- assertEquals(UserMgtException.Reason.GROUP_STILL_OCCUPIED,
- e.getReason());
+ assertEquals(UserMgtException.Reason.GROUP_STILL_OCCUPIED, e
+ .getReason());
return;
}
}
/**
- * Tries to remove an unknown group. Verifies that an exception is
- * thrown.
- *
- * @throws UserMgtException DOCUMENT ME!
+ * Tries to remove an unknown group. Verifies that an exception is thrown.
+ *
*/
public void testRemoveGroupUnknownGroup() throws UserMgtException {
- Group group = admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
Group group2 = new Group(GROUP2);
try {
/**
* Changes the password, verifies that this succeeds.
- *
+ *
* @throws UserMgtException
*/
public void testChangePassword() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ User user = admin.createUser(USER1, PASS1, group);
user.changePassword(PASS1, PASS2);
// retrieve the user and verifies the password hasn't changed.
/**
* Performance test. Finds a user by name.
- *
- * @throws UserMgtException DOCUMENT ME!
+ *
*/
public void testPerformanceFindUserByName() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
admin.createUser(USER1, PASS1, group);
- int n = 1000;
+ int n = 1000;
long time = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
admin.getUser(USER1);
}
- LOGGER.info("Looked up a user " + n + " times in "
- + ((float) (System.currentTimeMillis() - time) / 1000.0));
+ LOGGER.info("Looked up a user " + n + " times in " +
+ ((float) (System.currentTimeMillis() - time) / 1000.0));
}
}
import org.wamblee.usermgt.UserMgtException.Reason;
-
/**
* User management test utilities.
- *
+ *
* @author Erik Brakkee
*/
public class UsermgtTestUtils {
- /**
- * DOCUMENT ME!
- */
private static final String DUMMY_GROUP = "dummygroup";
- /**
- * DOCUMENT ME!
- */
private static final String DUMMY_PASSWD = "dummypasswd";
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public static Group createGroup(String aName) {
return new Group(aName);
}
- /**
- * DOCUMENT ME!
- *
- * @param aUsername DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
public static User createUser(String aUsername) throws UserMgtException {
return createUser(aUsername, DUMMY_GROUP);
}
- /**
- * DOCUMENT ME!
- *
- * @param aUsername DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
public static User createUser(String aUsername, String aGroup)
throws UserMgtException {
return createUser(aUsername, createGroup(aGroup));
}
- /**
- * DOCUMENT ME!
- *
- * @param aUsername DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
public static User createUser(String aUsername, Group aGroup)
throws UserMgtException {
return createUser(aUsername, DUMMY_PASSWD, aGroup);
}
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- * @param aPassword DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
public static User createUser(String aName, String aPassword, Group aGroup)
throws UserMgtException {
- return new User(aName, aPassword, aGroup,
- new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN,
- Reason.INVALID_PASSWORD, "Password must be at least 6 chars"),
- new Md5HexMessageDigester());
+ return new User(aName, aPassword, aGroup, new RegexpNameValidator(
+ RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD,
+ "Password must be at least 6 chars"), new Md5HexMessageDigester());
}
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
public static void addUserToGroup(User aUser, Group aGroup)
throws UserMgtException {
aUser.addGroup(aGroup);
}
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- * @param aGroup DOCUMENT ME!
- *
- * @throws UserMgtException DOCUMENT ME!
- */
public static void removeUserFromGroup(User aUser, Group aGroup)
throws UserMgtException {
aUser.removeGroup(aGroup);
import java.util.HashMap;
import java.util.Map;
-
/**
* Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet}
- *
+ *
* @author Erik Brakkee
*/
public class HibernateGroupSetTest extends InMemoryGroupSetTest {
- /**
- * DOCUMENT ME!
- */
private static final String GROUP_TABLE = "GROUPS";
- /**
- * DOCUMENT ME!
- */
- private static final String GROUP_QUERY = "select * from " + GROUP_TABLE
- + " where name = ?";
+ private static final String GROUP_QUERY = "select * from " + GROUP_TABLE +
+ " where name = ?";
- /**
- * DOCUMENT ME!
- */
private DefaultContainer container;
- /**
- * DOCUMENT ME!
- */
private Scope scope;
- /**
- * DOCUMENT ME!
- */
private DatabaseTesterComponent databaseTester;
- /**
- * DOCUMENT ME!
- */
private GroupSet groupSet;
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
container = new UserMgtRepositoryTestContainer("top");
- ObjectConfiguration config = new ObjectConfiguration(HibernateGroupSetTest.class);
- config.getSetterConfig().clear().add("setGroupSet")
- .add("setDatabaseTester");
+ ObjectConfiguration config = new ObjectConfiguration(
+ HibernateGroupSetTest.class);
+ config.getSetterConfig().clear().add("setGroupSet").add(
+ "setDatabaseTester");
container.addComponent("testcase", this, config);
scope = container.start();
super.setUp();
}
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void tearDown() throws Exception {
container.stop(scope);
super.tearDown();
}
- /**
- * DOCUMENT ME!
- *
- * @param aDatabaseTester DOCUMENT ME!
- */
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
databaseTester = aDatabaseTester;
}
- /**
- * DOCUMENT ME!
- *
- * @param aGroupSet DOCUMENT ME!
- */
public void setGroupSet(GroupSet aGroupSet) {
groupSet = aGroupSet;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aSize DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
- */
@Override
protected void checkGroupCount(int aSize) throws SQLException {
databaseTester.flush();
assertEquals(aSize, databaseTester.getTableSize(GROUP_TABLE));
}
- /* (non-Javadoc)
- * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String
+ * )
*/
@Override
- protected void checkGroupExists(final String aGroup)
- throws SQLException {
+ protected void checkGroupExists(final String aGroup) throws SQLException {
databaseTester.flush();
- Map<String, Integer> result = 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);
- Map<String, Integer> res = new HashMap<String, Integer>();
- res.put("result", databaseTester.countResultSet(result));
-
- return res;
- }
- });
+ Map<String, Integer> result = 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);
+ Map<String, Integer> res = new HashMap<String, Integer>();
+ res.put("result", databaseTester.countResultSet(result));
+
+ return res;
+ }
+ });
int count = result.get("result");
assertEquals(1, count);
}
- /* (non-Javadoc)
- * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang
+ * .String)
*/
@Override
protected void checkGroupNotExists(String aGroup) throws SQLException {
assertEquals(0, databaseTester.countResultSet(result));
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#createGroupSet()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected GroupSet createGroupSet() {
return groupSet;
import java.sql.SQLException;
-
/**
- * User administration tests with persistence based on Hibernate. This
- * executes the same test cases as {@link
- * org.wamblee.usermgt.UserAdministrationImplTest} with in addition, one test
- * case that executes all Hibernate test cases separately with each test case
- * in its own transaction.
- *
+ * User administration tests with persistence based on Hibernate. This executes
+ * the same test cases as {@link org.wamblee.usermgt.UserAdministrationImplTest}
+ * with in addition, one test case that executes all Hibernate test cases
+ * separately with each test case in its own transaction.
+ *
* @author Erik Brakkee
*/
public class HibernateUserAdministrationTest extends UserAdministrationImplTest {
- /**
- * DOCUMENT ME!
- */
- private static final Log LOG = LogFactory.getLog(HibernateUserAdministrationTest.class);
+ private static final Log LOG = LogFactory
+ .getLog(HibernateUserAdministrationTest.class);
- /**
- * DOCUMENT ME!
- */
private DefaultContainer container;
- /**
- * DOCUMENT ME!
- */
private Scope scope;
- /**
- * DOCUMENT ME!
- */
private DatabaseTesterComponent databaseTester;
- /**
- * DOCUMENT ME!
- */
private EhCache<Serializable, Serializable> userCache;
- /**
- * DOCUMENT ME!
- */
private UserAdministration userAdmin;
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.usermgt.UserAdministrationImplTest#setUp()
*/
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
container = new DefaultContainer("top");
container.addComponent(new DatasourceComponent("datasource"));
container.addComponent(new UserAdministrationComponent("admin", true));
- ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class);
+ ClassConfiguration dbtesterConfig = new ClassConfiguration(
+ DatabaseTesterComponent.class);
dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
container.addComponent("databaseTester", dbtesterConfig);
- ObjectConfiguration config = new ObjectConfiguration(HibernateUserAdministrationTest.class);
- config.getSetterConfig().clear().add("setUserCache")
- .add("setDatabaseTester").add("setUserAdmin");
+ ObjectConfiguration config = new ObjectConfiguration(
+ HibernateUserAdministrationTest.class);
+ config.getSetterConfig().clear().add("setUserCache").add(
+ "setDatabaseTester").add("setUserAdmin");
container.addComponent("testcase", this, config);
scope = container.start();
clearUserCache();
}
- /**
- * DOCUMENT ME!
- *
- * @param aUserCache DOCUMENT ME!
- */
public void setUserCache(EhCache<Serializable, Serializable> aUserCache) {
userCache = aUserCache;
}
- /**
- * DOCUMENT ME!
- *
- * @param aDatabaseTester DOCUMENT ME!
- */
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
databaseTester = aDatabaseTester;
}
- /**
- * DOCUMENT ME!
- *
- * @param aUserAdmin DOCUMENT ME!
- */
public void setUserAdmin(UserAdministration aUserAdmin) {
userAdmin = aUserAdmin;
}
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void tearDown() throws Exception {
container.stop(scope);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministrationImplTest#createAdmin()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected UserAdministration createAdmin() {
return userAdmin;
}
- /**
- * DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
- * @throws RuntimeException DOCUMENT ME!
- */
public void testAllTestsInASeparateTransaction() throws SQLException {
Method[] methods = UserAdministrationImplTest.class.getMethods();
if (method.getName().startsWith("test")) {
databaseTester.cleanDatabase();
clearUserCache();
- databaseTester.executeTransaction(new TestTransactionCallbackWithoutResult() {
+ databaseTester
+ .executeTransaction(new TestTransactionCallbackWithoutResult() {
public void execute() throws Exception {
LOG.info("Running test " + method.getName());
try {
- method.invoke(HibernateUserAdministrationTest.this);
+ method
+ .invoke(HibernateUserAdministrationTest.this);
} catch (Throwable t) {
- LOG.error("Test " + method.getName()
- + " failed");
+ LOG.error("Test " + method.getName() +
+ " failed");
throw new RuntimeException(t.getMessage(), t);
} finally {
- LOG.info("Test " + method.getName()
- + " finished");
+ LOG.info("Test " + method.getName() +
+ " finished");
}
}
});
}
}
- /**
- *
- */
private void clearUserCache() {
userCache.clear();
}
import java.util.Set;
-
/**
* Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet}
- *
+ *
* @author Erik Brakkee
*/
public class HibernateUserSetTest extends InMemoryUserSetTest {
- /**
- * DOCUMENT ME!
- */
private static final String USER_TABLE = "USERS";
- /**
- * DOCUMENT ME!
- */
private static final String GROUP_TABLE = "GROUPS";
- /**
- * DOCUMENT ME!
- */
- private static final String USER_QUERY = "select * from " + USER_TABLE
- + " where name = ?";
+ private static final String USER_QUERY = "select * from " + USER_TABLE +
+ " where name = ?";
- /**
- * DOCUMENT ME!
- */
- private static final String GROUP_QUERY = "select * from " + GROUP_TABLE
- + " where name = ?";
+ private static final String GROUP_QUERY = "select * from " + GROUP_TABLE +
+ " where name = ?";
- /**
- * DOCUMENT ME!
- */
private DefaultContainer container;
- /**
- * DOCUMENT ME!
- */
private Scope scope;
- /**
- * DOCUMENT ME!
- */
private UserSet userset;
- /**
- * DOCUMENT ME!
- */
private GroupSet groupset;
- /**
- * DOCUMENT ME!
- */
private EhCache<Serializable, Serializable> userCache;
- /**
- * DOCUMENT ME!
- */
private DatabaseTesterComponent databaseTester;
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryUserSetTest#setUp()
*/
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
container = new UserMgtRepositoryTestContainer("top");
- ObjectConfiguration config = new ObjectConfiguration(HibernateUserSetTest.class);
+ ObjectConfiguration config = new ObjectConfiguration(
+ HibernateUserSetTest.class);
config.getSetterConfig().clear().add("setUserset").add("setGroupset")
- .add("setDatabaseTester").add("setUserCache");
+ .add("setDatabaseTester").add("setUserCache");
container.addComponent("testcase", this, config);
scope = container.start();
super.setUp();
}
- /**
- * DOCUMENT ME!
- *
- * @param aUserset DOCUMENT ME!
- */
public void setUserset(UserSet aUserset) {
userset = aUserset;
}
- /**
- * DOCUMENT ME!
- *
- * @param aGroupset DOCUMENT ME!
- */
public void setGroupset(GroupSet aGroupset) {
groupset = aGroupset;
}
- /**
- * DOCUMENT ME!
- *
- * @param aUserCache DOCUMENT ME!
- */
public void setUserCache(EhCache<Serializable, Serializable> aUserCache) {
userCache = aUserCache;
}
- /**
- * DOCUMENT ME!
- *
- * @param aDatabaseTester DOCUMENT ME!
- */
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
databaseTester = aDatabaseTester;
}
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void tearDown() throws Exception {
container.stop(scope);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aSize DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
- */
@Override
protected void checkUserCount(int aSize) throws SQLException {
databaseTester.flush();
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String
+ * )
*/
@Override
protected void checkUserExists(String aUser) throws SQLException {
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aUser DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang
+ * .String)
*/
@Override
protected void checkUserNotExists(String aUser) throws SQLException {
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aSize DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
- */
@Override
protected void checkGroupCount(int aSize) throws SQLException {
databaseTester.flush();
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String
+ * )
*/
@Override
protected void checkGroupExists(String aGroup) throws SQLException {
/*
* (non-Javadoc)
- *
- * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aGroup DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang
+ * .String)
*/
@Override
protected void checkGroupNotExists(String aGroup) throws SQLException {
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#createGroupSet()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected UserSet createUserSet() {
return userset;
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryUserSetTest#createGroupSet()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected GroupSet createGroupSet() {
return groupset;
}
/**
- * Reproduction of a bug. Create a user which is in group1 Add it
- * to a second group group2. Remove the user from group1. Verify the user
- * is in group2.
- *
- * @throws SQLException DOCUMENT ME!
- * @throws UserMgtException DOCUMENT ME!
+ * Reproduction of a bug. Create a user which is in group1 Add it to a
+ * second group group2. Remove the user from group1. Verify the user is in
+ * group2.
+ *
*/
public void testVerifyAddRemove() throws SQLException, UserMgtException {
databaseTester.cleanDatabase(); // just to be sure.
getUsers().userModified(user);
clearUserCache();
- User user2 = getUsers().find("user");
+ User user2 = getUsers().find("user");
Set<Group> userGroups = user2.getGroups();
assertTrue(user2.isInGroup("group1"));
assertTrue(user2.isInGroup("group2"));
removeUserFromGroup(user, group1);
getUsers().userModified(user);
clearUserCache();
- user2 = getUsers().find("user");
- userGroups = user2.getGroups();
+ user2 = getUsers().find("user");
+ userGroups = user2.getGroups();
assertFalse(user2.isInGroup("group1"));
assertTrue(user2.isInGroup("group2"));
assertEquals(1, userGroups.size());
import java.io.IOException;
-
/**
* Test container for repository tests of user management.
- *
+ *
* @author Erik Brakkee
*/
public class UserMgtRepositoryTestContainer extends DefaultContainer {
-/**
+ /**
* Creates a new UserMgtRepositoryTestContainer object.
- *
- * @param aName DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
+ *
+ *
*/
- public UserMgtRepositoryTestContainer(String aName)
- throws IOException {
+ public UserMgtRepositoryTestContainer(String aName) throws IOException {
super(aName);
DatabaseComponentFactory.addDatabaseConfig(this);
addComponent(new DatasourceComponent("datasource"));
- ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class);
+ ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(
+ UsermgtHibernateMappingFiles.class);
mappingFilesConfig.getSetterConfig().initAllSetters();
addComponent("mappingFiles", new UsermgtHibernateMappingFiles(),
mappingFilesConfig);
addComponent(new HibernateComponent("hibernate"));
addComponent(new UserGroupRepositoryComponent("usersgroups"));
- ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class);
+ ClassConfiguration dbtesterConfig = new ClassConfiguration(
+ DatabaseTesterComponent.class);
dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
addComponent("databaseTester", dbtesterConfig);
}
import java.io.Serializable;
-
/**
- * The <code>Cache</code> interface represents... a cache.
- * In some circumstances it is more optimal to implement caching directly in
- * the code instead of relying on Hibernate caching methods. This interface abstracts
- * from the used cache implementation.
- * Cache implementations must be thread-safe.
+ * The <code>Cache</code> interface represents... a cache. In some circumstances
+ * it is more optimal to implement caching directly in the code instead of
+ * relying on Hibernate caching methods. This interface abstracts from the used
+ * cache implementation. Cache implementations must be thread-safe.
*/
public interface Cache<KeyType extends Serializable, ValueType extends Serializable> {
/**
* Adds a key-value pair to the cache.
- *
- * @param aKey Key.
- * @param aValue Value.
+ *
+ * @param aKey
+ * Key.
+ * @param aValue
+ * Value.
*/
void put(KeyType aKey, ValueType aValue);
/**
* Retrieves a value from the cache.
- *
- * @param aKey Key to retrieve.
- *
+ *
+ * @param aKey
+ * Key to retrieve.
+ *
* @return Key.
*/
ValueType get(KeyType aKey);
/**
* Removes an entry from the cache.
- *
- * @param aKey Key to remove the entry for.
+ *
+ * @param aKey
+ * Key to remove the entry for.
*/
void remove(KeyType aKey);
import java.io.Serializable;
-
/**
- * Represents a cached object. The object is either retrieved from the
- * cache if the cache has it, or a call back is invoked to get the object (and
- * put it in the cache).
- *
+ * Represents a cached object. The object is either retrieved from the cache if
+ * the cache has it, or a call back is invoked to get the object (and put it in
+ * the cache).
+ *
* @author Erik Brakkee
- *
- * @param <KeyType> DOCUMENT ME!
- * @param <ValueType> DOCUMENT ME!
+ *
*/
public class CachedObject<KeyType extends Serializable, ValueType extends Serializable> {
- /**
- * DOCUMENT ME!
- */
private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
/**
private KeyType objectKey;
/**
- * Computation used to obtain the object if it is not found in the
- * cache.
+ * Computation used to obtain the object if it is not found in the cache.
*/
private Computation<KeyType, ValueType> computation;
-/**
+ /**
* Constructs the cached object.
- *
+ *
* @param aCache
* Cache to use.
* @param aObjectKey
*/
public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
Computation<KeyType, ValueType> aComputation) {
- cache = aCache;
- objectKey = aObjectKey;
- computation = aComputation;
+ cache = aCache;
+ objectKey = aObjectKey;
+ computation = aComputation;
}
/**
- * Gets the object. Since the object is cached, different calls to
- * this method may return different objects.
- *
+ * Gets the object. Since the object is cached, different calls to this
+ * method may return different objects.
+ *
* @return Object.
*/
public ValueType get() {
ValueType object = (ValueType) cache.get(objectKey); // the used
- // cache is
- // thread safe.
+ // cache is
+ // thread safe.
if (object == null) {
// synchronize the computation to make sure that the object is only
}
/**
- * Invalidates the cache for the object so that it is recomputed
- * the next time it is requested.
+ * Invalidates the cache for the object so that it is recomputed the next
+ * time it is requested.
*/
public void invalidate() {
cache.remove(objectKey);
/**
* Gets the cache.
- *
+ *
* @return Cache.
*/
public Cache getCache() {
return cache;
}
-/**
+ /**
* Callback invoked to compute an object if it was not found in the cache.
- *
+ *
* @param <T>
* Type of the object
*/
public static interface Computation<Key extends Serializable, Value extends Serializable> {
/**
- * Gets the object. Called when the object is not in the
- * cache.
- *
- * @param aObjectKey Id of the object in the cache.
- *
+ * Gets the object. Called when the object is not in the cache.
+ *
+ * @param aObjectKey
+ * Id of the object in the cache.
+ *
* @return Object, must be non-null.
*/
Value getObject(Key aObjectKey);
import java.io.InputStream;
import java.io.Serializable;
-
/**
* Cache implemented on top of EhCache.
- *
+ *
* @author Erik Brakkee
- *
- * @param <KeyType> DOCUMENT ME!
- * @param <ValueType> DOCUMENT ME!
+ *
*/
public class EhCache<KeyType extends Serializable, ValueType extends Serializable>
implements org.wamblee.cache.Cache<KeyType, ValueType> {
- /**
- * DOCUMENT ME!
- */
private static final Logger LOGGER = Logger.getLogger(EhCache.class);
/**
*/
private Cache cache;
-/**
+ /**
* Constructs a cache based on EHCache.
- *
+ *
* @param aResource
* Resource containing the configuration file for EHCache.
* @param aCacheName
InputStream is = aResource.getInputStream();
try {
- manager = new CacheManager(is);
- cache = manager.getCache(aCacheName);
+ manager = new CacheManager(is);
+ cache = manager.getCache(aCacheName);
if (cache == null) {
- LOGGER.warn("Creating cache '" + aCacheName
- + "' because it is not configured");
+ LOGGER.warn("Creating cache '" + aCacheName +
+ "' because it is not configured");
manager.addCache(aCacheName);
cache = manager.getCache(aCacheName);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#put(KeyType, ValueType)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- * @param aValue DOCUMENT ME!
- */
public void put(KeyType aKey, ValueType aValue) {
cache.put(new Element(aKey, aValue));
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#get(KeyType)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public ValueType get(KeyType aKey) {
try {
Element element = cache.get(aKey);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#remove(KeyType)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- */
public void remove(KeyType aKey) {
cache.remove(aKey);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#clear()
*/
- /**
- * DOCUMENT ME!
- */
public void clear() {
cache.removeAll();
}
import java.util.HashMap;
-
/**
- * A very simple cache based on a HashMap, It never expires any entries,
- * and has no bounds on its size.
- *
+ * A very simple cache based on a HashMap, It never expires any entries, and has
+ * no bounds on its size.
+ *
* @author Erik Brakkee
- *
- * @param <KeyType> DOCUMENT ME!
- * @param <ValueType> DOCUMENT ME!
+ *
*/
public class ForeverCache<KeyType extends Serializable, ValueType extends Serializable>
implements Cache<KeyType, ValueType> {
*/
private HashMap<KeyType, ValueType> map;
-/**
+ /**
* Constructs the cache.
- *
+ *
*/
public ForeverCache() {
map = new HashMap<KeyType, ValueType>();
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#put(KeyType, ValueType)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- * @param aValue DOCUMENT ME!
- */
public synchronized void put(KeyType aKey, ValueType aValue) {
map.put(aKey, aValue);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#get(KeyType)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public synchronized ValueType get(KeyType aKey) {
return map.get(aKey);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#remove(KeyType)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- */
public synchronized void remove(KeyType aKey) {
map.remove(aKey);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#clear()
*/
- /**
- * DOCUMENT ME!
- */
public synchronized void clear() {
map.clear();
}
import java.io.Serializable;
-
/**
* A cache that does not cache. This implementation is useful for disabling
* caching. Because of this implementation, application code does not need to
* distinguish between the situation where it a cache is used and where it
* isn't.
- *
+ *
* @author Erik Brakkee
- *
- * @param <KeyType> DOCUMENT ME!
- * @param <ValueType> DOCUMENT ME!
+ *
*/
public class ZeroCache<KeyType extends Serializable, ValueType extends Serializable>
implements Cache<KeyType, ValueType> {
* Creates a new ZeroCache object.
*/
public ZeroCache() {
- // Empty.
+ // Empty.
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.cache.Cache#put(KeyType, ValueType)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- * @param aValue DOCUMENT ME!
- */
public void put(KeyType aKey, ValueType aValue) {
- // Empty.
+ // Empty.
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.cache.Cache#get(KeyType)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public ValueType get(KeyType aKey) {
return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.cache.Cache#remove(KeyType)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- */
public void remove(KeyType aKey) {
- // Empty
+ // Empty
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.cache.Cache#clear()
*/
- /**
- * DOCUMENT ME!
- */
public void clear() {
- // Empty
+ // Empty
}
}
import java.util.Collection;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class CollectionFilter {
/**
- * Filters a collection by adding all elements in the from
- * collection that satisfy a given condition to the to collection.
- *
- * @param <T> Type of contained element.
- * @param aFrom From container to which the condition is applied.
- * @param aTo To container to which matching elements are added.
- * @param aCondition Condition by which elements are matched.
+ * Filters a collection by adding all elements in the from collection that
+ * satisfy a given condition to the to collection.
+ *
+ * @param <T>
+ * Type of contained element.
+ * @param aFrom
+ * From container to which the condition is applied.
+ * @param aTo
+ * To container to which matching elements are added.
+ * @param aCondition
+ * Condition by which elements are matched.
*/
public static <T> void filter(Collection<T> aFrom, Collection<T> aTo,
Condition<T> aCondition) {
import java.util.concurrent.locks.ReentrantLock;
-
/**
* In memory JVM lock.
- *
+ *
* @author Erik Brakkee
*/
public class JvmLock implements Lock {
lock = new ReentrantLock(true);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.concurrency.Lock#acquire()
*/
public void acquire() {
lock.lock();
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.concurrency.Lock#release()
*/
public void release() {
*/
package org.wamblee.concurrency;
-
/**
- * Represents a re-entrant lock.
- * Implementations can provide inmemory JVM locking or full cluster safe locking
- * mechanisms.
- *
+ * Represents a re-entrant lock. Implementations can provide inmemory JVM
+ * locking or full cluster safe locking mechanisms.
+ *
* @author Erik Brakkee
*/
public interface Lock {
import java.util.HashSet;
-
/**
* Read-write lock for allowing multiple concurrent readers or at most one
* writer. This implementation does not aim for high performance but for
*/
public class ReadWriteLock {
/**
- * Sets containing the references to the threads that are currently
- * reading. This administration is useful to check that the lock has
- * already been acquired before it is release. This check adds robustness
- * to the application.
+ * Sets containing the references to the threads that are currently reading.
+ * This administration is useful to check that the lock has already been
+ * acquired before it is release. This check adds robustness to the
+ * application.
*/
private HashSet<Thread> readers;
}
/**
- * Acquires the lock for reading. This call will block until the lock can
- * be acquired.
- *
- * @throws IllegalStateException Thrown if the read or write lock is
- * already acquired.
+ * Acquires the lock for reading. This call will block until the lock can be
+ * acquired.
+ *
+ * @throws IllegalStateException
+ * Thrown if the read or write lock is already acquired.
*/
public synchronized void acquireRead() {
if (readers.contains(Thread.currentThread())) {
throw new IllegalStateException(
"Read lock already acquired by current thread: " +
- Thread.currentThread());
+ Thread.currentThread());
}
if (writer == Thread.currentThread()) {
throw new IllegalStateException(
"Trying to acquire the read lock while already holding a write lock: " +
- Thread.currentThread());
+ Thread.currentThread());
}
while (writer != null) {
}
/**
- * Releases the lock for reading. Note: This implementation assumes that
- * the lock has already been acquired for reading previously.
- *
- * @throws IllegalStateException Thrown when the lock was not acquired by
- * this thread.
+ * Releases the lock for reading. Note: This implementation assumes that the
+ * lock has already been acquired for reading previously.
+ *
+ * @throws IllegalStateException
+ * Thrown when the lock was not acquired by this thread.
*/
public synchronized void releaseRead() {
if (!readers.remove(Thread.currentThread())) {
/**
* Acquires the lock for writing. This call will block until the lock has
* been acquired.
- *
- * @throws IllegalStateException Thrown if the read or write lock is
- * already acquired.
+ *
+ * @throws IllegalStateException
+ * Thrown if the read or write lock is already acquired.
*/
public synchronized void acquireWrite() {
if (writer == Thread.currentThread()) {
throw new IllegalStateException(
"Trying to acquire a write lock while already holding the write lock: " +
- Thread.currentThread());
+ Thread.currentThread());
}
if (readers.contains(Thread.currentThread())) {
throw new IllegalStateException(
"Trying to acquire a write lock while already holding the read lock: " +
- Thread.currentThread());
+ Thread.currentThread());
}
// wait until there are no more writers and no more
- // readers
+ // readers
while ((writer != null) || (readers.size() > 0)) {
try {
wait();
/**
* Releases the lock for writing.
- *
- * @throws IllegalStateException Thrown when the lock was not acquired.
+ *
+ * @throws IllegalStateException
+ * Thrown when the lock was not acquired.
*/
public synchronized void releaseWrite() {
if (writer != Thread.currentThread()) {
import java.util.ArrayList;
import java.util.List;
-
/**
* Represents a logical and of different boolean conditions.
- *
+ *
* @author Erik Brakkee
- *
- * @param <T> DOCUMENT ME!
+ *
*/
public class AndCondition<T> implements Condition<T> {
- /**
- * DOCUMENT ME!
- */
private List<Condition<T>> conditions;
-/**
+ /**
* Constructs the condition.
- *
+ *
* @param aCondition1
* First condition.
* @param aCondition2
conditions.add(aCondition2);
}
-/**
+ /**
* Constructs the and condition.
- *
+ *
* @param aConditions
* List of conditions to use in the logical and.
*/
/*
* (non-Javadoc)
- *
- * @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aObject DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss
+ * .Program)
*/
public boolean matches(T aObject) {
for (Condition<T> condition : conditions) {
/**
* Determines if an object matches a certain condition.
- *
+ *
* @author Erik Brakkee
*/
public interface Condition<T> {
/**
* Determines if an object matches a condition.
- *
- * @param aObject object to match.
- *
+ *
+ * @param aObject
+ * object to match.
+ *
* @return True iff the object matches.
*/
boolean matches(T aObject);
/**
* Condition which always returns a fixed value.
- *
+ *
* @author Erik Brakkee
- *
- * @param <T> DOCUMENT ME!
+ *
*/
public class FixedCondition<T> implements Condition<T> {
- /**
- * DOCUMENT ME!
- */
private boolean value;
-/**
+ /**
* Constructs the condition.
- * @param aValue Fixed value of the condition.
+ *
+ * @param aValue
+ * Fixed value of the condition.
*/
public FixedCondition(boolean aValue) {
value = aValue;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.conditions.Condition#matches(T)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aObject DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean matches(T aObject) {
return value;
}
import java.util.ArrayList;
import java.util.List;
-
/**
* Represents a logical or of different boolean conditions.
- *
+ *
* @author Erik Brakkee
- *
- * @param <T> DOCUMENT ME!
+ *
*/
public class OrCondition<T> implements Condition<T> {
- /**
- * DOCUMENT ME!
- */
private List<Condition<T>> conditions;
-/**
+ /**
* Constructs the condition.
- *
+ *
* @param aCondition1
* First condition.
* @param aCondition2
conditions.add(aCondition2);
}
-/**
+ /**
* Constructs the or condition.
- *
+ *
* @param aConditions
* List of conditions to use in the logical or.
*/
/*
* (non-Javadoc)
- *
- * @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aObject DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ *
+ * @see
+ * org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss
+ * .Program)
*/
public boolean matches(T aObject) {
for (Condition<T> condition : conditions) {
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
/**
- * Condition to check whether a given property value matches a certain
- * regular expression.
- *
+ * Condition to check whether a given property value matches a certain regular
+ * expression.
+ *
* @author Erik Brakkee
- *
- * @param <T> DOCUMENT ME!
+ *
*/
public class PropertyRegexCondition<T> implements Condition<T> {
/**
private Pattern regex;
/**
- * Whether or not to convert the value to lowercase before
- * matching.
+ * Whether or not to convert the value to lowercase before matching.
*/
private boolean tolower;
-/**
+ /**
* Constructs the condition.
- * @param aProperty Name of the property to examine.
- * @param aRegex Regular expression to use.
- * @param aTolower Whether or not to convert the value to lowercase before matching.
+ *
+ * @param aProperty
+ * Name of the property to examine.
+ * @param aRegex
+ * Regular expression to use.
+ * @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)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.conditions.Condition#matches(T)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aObject DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean matches(T aObject) {
try {
String value = PropertyUtils.getProperty(aObject, property) + "";
*/
package org.wamblee.general;
-
/**
* Bean factory used to obtain objects in a transparent way.
- *
+ *
* @author Erik Brakkee
*/
public interface BeanFactory {
/**
* Finds a bean based on id.
- * @param aId Id of the bean.
- * @return Object (always non-null).
- * @throws BeanFactoryException In case the object could not be found.
+ *
+ * @param aId
+ * Id of the bean.
+ * @return Object (always non-null).
+ * @throws BeanFactoryException
+ * In case the object could not be found.
*/
Object find(String aId);
/**
* Exception thrown by the BeanFactory if an object could not be found.
- *
+ *
* @author Erik Brakkee
*/
public class BeanFactoryException extends RuntimeException {
- /**
- * DOCUMENT ME!
- */
static final long serialVersionUID = -1215992188624874902L;
-/**
+ /**
* Constructs the exception.
- * @param aMsg Message.
+ *
+ * @param aMsg
+ * Message.
*/
public BeanFactoryException(String aMsg) {
super(aMsg);
}
-/**
+ /**
* Constructs the exception.
- * @param aMsg Message.
- * @param aThrowable Cause of the exception.
+ *
+ * @param aMsg
+ * Message.
+ * @param aThrowable
+ * Cause of the exception.
*/
public BeanFactoryException(String aMsg, Throwable aThrowable) {
super(aMsg, aThrowable);
import java.util.Properties;
-
/**
* The standard means to obtain the bean factory. This works by reading a
- * property {@value #BEAN_FACTORY_CLASS} from a property file named {@value
- * #BEAN_KERNEL_PROP_FILE} from the class path. This property identifies the
- * bean factory implementation to use. The configured bean factory must have a
- * no-arg constructor.
+ * property {@value #BEAN_FACTORY_CLASS} from a property file named
+ * {@value #BEAN_KERNEL_PROP_FILE} from the class path. This property identifies
+ * the bean factory implementation to use. The configured bean factory must have
+ * a no-arg constructor.
*/
public final class BeanKernel {
- /**
- * DOCUMENT ME!
- */
private static final Log LOG = LogFactory.getLog(BeanKernel.class);
/**
private static final String BEAN_KERNEL_PROP_FILE = "org.wamblee.beanfactory.properties";
/**
- * Name of the property to define the name of the bean factory
- * class to use. THis class must have a public default constructor.
+ * Name of the property to define the name of the bean factory class to use.
+ * THis class must have a public default constructor.
*/
private static final String BEAN_FACTORY_CLASS = "org.wamblee.beanfactory.class";
*/
private static BeanFactory BEAN_FACTORY;
-/**
+ /**
* Disabled constructor.
- *
+ *
*/
private BeanKernel() {
// Empty
}
/**
- * Overrides the default mechanism for looking up the bean factory
- * by specifying it yourself.
- *
- * @param aOverride Override bean factory.
+ * Overrides the default mechanism for looking up the bean factory by
+ * specifying it yourself.
+ *
+ * @param aOverride
+ * Override bean factory.
*/
public static void overrideBeanFactory(BeanFactory aOverride) {
BEAN_FACTORY = aOverride;
/**
* Gets the bean factory.
- *
+ *
* @return Bean factory.
*/
public static BeanFactory getBeanFactory() {
/**
* Lookup the bean factory based on the properties file.
- *
- * @param aPropertyFilename DOCUMENT ME!
- *
+ *
+ *
* @return Bean factory.
- *
- * @throws BeanFactoryException DOCUMENT ME!
+ *
*/
static BeanFactory lookupBeanFactory(String aPropertyFilename) {
InputResource resource = new ClassPathResource(aPropertyFilename);
- InputStream is;
+ InputStream is;
try {
- is = resource.getInputStream();
+ is = resource.getInputStream();
} catch (IOException e) {
- throw new BeanFactoryException("Cannot open resource " + resource, e);
+ throw new BeanFactoryException("Cannot open resource " + resource,
+ e);
}
try {
Properties props = new Properties();
props.load(is);
- String className = props.getProperty(BEAN_FACTORY_CLASS);
- Class beanFactory = Class.forName(className);
+ String className = props.getProperty(BEAN_FACTORY_CLASS);
+ Class beanFactory = Class.forName(className);
return (BeanFactory) beanFactory.newInstance();
} catch (Exception e) {
- throw new BeanFactoryException("Cannot read from resource "
- + resource, e);
+ throw new BeanFactoryException("Cannot read from resource " +
+ resource, e);
} finally {
try {
is.close();
import java.net.URL;
import java.net.URLClassLoader;
-
/**
* Utility for working with the class loader. Based on the ClassPathHacker
* example found on the internet.
public class ClassLoaderUtils {
// No logging in this class to keep the required class libraries
// limited to the standard java classes. This allows use of the
- // utilities in an environment with a very limited classpath.
+ // utilities in an environment with a very limited classpath.
private static final String JAR_SUFFIX = ".jar";
/**
* Adds all jars in the given directory to the class path.
- * @param aDirectory Directory.
+ *
+ * @param aDirectory
+ * Directory.
* @throws IOException
*/
- public static void addJarsInDirectory(File aDirectory)
- throws IOException {
+ public static void addJarsInDirectory(File aDirectory) throws IOException {
System.out.println("directory '" + aDirectory + "'");
for (File aFile : aDirectory.listFiles()) {
- System.out.println("Considering '" + aFile.getCanonicalPath() +
- "'");
+ System.out
+ .println("Considering '" + aFile.getCanonicalPath() + "'");
if (aFile.getName().toLowerCase().endsWith(JAR_SUFFIX)) {
System.out.println("Adding '" + aFile.getCanonicalPath() +
/**
* Adds a file to the classpath.
- * @param aFilename Filename to add.
+ *
+ * @param aFilename
+ * Filename to add.
* @throws IOException
*/
public static void addFile(String aFilename) throws IOException {
/**
* Adds a file to the classpath.
- * @param aFile File to add.
+ *
+ * @param aFile
+ * File to add.
* @throws IOException
*/
public static void addFile(File aFile) throws IOException {
/**
* Adds a url to the classpath.
- * @param aUrl Url to add.
+ *
+ * @param aUrl
+ * Url to add.
* @throws IOException
*/
public static void addURL(URL aUrl) throws IOException {
- URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
+ URLClassLoader sysloader = (URLClassLoader) ClassLoader
+ .getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL",
- new Class[] { URL.class });
+ new Class[] { URL.class });
method.setAccessible(true);
method.invoke(sysloader, new Object[] { aUrl });
} catch (Throwable t) {
*/
package org.wamblee.general;
-
/**
* Represents a pair of objects. This is inspired on the C++ Standard Template
* Library pair template.
- *
+ *
* @param <T>
* Type of the first object.
* @param <U>
* Type of the second object.
- *
+ *
* @author Erik Brakkee
*/
public class Pair<T, U> {
/**
* Constructs the pair.
- *
+ *
* @param aT
* First object.
* @param aU
/**
* Copies a pair.
- *
+ *
* @param aPair
* Pair to copy.
*/
/**
* Gets the first object of the pair.
- *
+ *
* @return First object.
*/
public T getFirst() {
/**
* Gets the second object of the pair.
- *
+ *
* @return Second object.
*/
public U getSecond() {
import java.io.IOException;
import java.io.InputStream;
-
/**
* Represents an input resource in the classpath.
*/
*/
private String resource;
-/**
+ /**
* Construct the class path resource.
- *
+ *
* @param aResource
* Resource
*/
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.io.InputResource#getInputStream()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
public InputStream getInputStream() throws IOException {
InputStream stream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(resource);
if (stream == null) {
- throw new IOException("Class path resource '" + resource
- + "' not found.");
+ throw new IOException("Class path resource '" + resource +
+ "' not found.");
}
return stream;
/*
* (non-Javadoc)
- *
+ *
* @see java.lang.Object#toString()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String toString() {
return "ClassPathResource(" + resource + ")";
}
import java.util.Map;
import java.util.Set;
-
/**
* Monitors a directory for changes.
- *
+ *
* @author Erik Brakkee
*/
public class DirectoryMonitor {
- /**
- * DOCUMENT ME!
- */
private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
- /**
- * DOCUMENT ME!
- */
private File directory;
- /**
- * DOCUMENT ME!
- */
private FileFilter filter;
- /**
- * DOCUMENT ME!
- */
private Listener listener;
- /**
- * DOCUMENT ME!
- */
private Map<File, Date> contents;
-/**
+ /**
* Creates a new DirectoryMonitor object.
- *
- * @param aDirectory DOCUMENT ME!
- * @param aFilefilter DOCUMENT ME!
- * @param aListener DOCUMENT ME!
+ *
*/
public DirectoryMonitor(File aDirectory, FileFilter aFilefilter,
Listener aListener) {
directory = aDirectory;
if (!directory.isDirectory()) {
- throw new IllegalArgumentException("Directory '" + directory
- + "' does not exist");
+ 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>();
}
/**
- * Polls the directory for changes and notifies the listener of any
- * changes. In case of any exceptions thrown by the listener while
- * handling the changes, the next call to this method will invoked the
- * listeners again for the same changes.
+ * Polls the directory for changes and notifies the listener of any changes.
+ * In case of any exceptions thrown by the listener while handling the
+ * changes, the next call to this method will invoked the listeners again
+ * for the same changes.
*/
public void poll() {
LOG.debug("Polling " + directory);
- Map<File, Date> newContents = new HashMap<File, Date>();
- File[] files = directory.listFiles(filter);
+ Map<File, Date> newContents = new HashMap<File, Date>();
+ File[] files = directory.listFiles(filter);
- // Check deleted files.
- Set<File> deletedFiles = new HashSet<File>(contents.keySet());
+ // Check deleted files.
+ Set<File> deletedFiles = new HashSet<File>(contents.keySet());
for (File file : files) {
if (file.isFile()) {
import java.io.IOException;
import java.io.InputStream;
-
/**
* Resource implemention for reading from a file.
- *
+ *
* @author Erik Brakkee
*/
public class FileResource implements InputResource {
*/
private File file;
-/**
+ /**
* Constructs the resource.
- *
+ *
* @param aFile
* File to read.
*/
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.io.InputResource#getInputStream()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
public InputStream getInputStream() throws IOException {
return new BufferedInputStream(new FileInputStream(file));
}
import java.io.IOException;
import java.io.InputStream;
-
/**
* Represents a resource from which information can be read.
- *
+ *
* @author Erik Brakkee
*/
public interface InputResource {
/**
- * Gets the input stream to the resource. The obtained input stream
- * must be closed once reading has finished.
- *
+ * Gets the input stream to the resource. The obtained input stream must be
+ * closed once reading has finished.
+ *
* @return Input stream to the resource, never null.
- *
- * @throws IOException in case the resource cannot be found.
+ *
+ * @throws IOException
+ * in case the resource cannot be found.
*/
InputStream getInputStream() throws IOException;
}
import java.io.StringWriter;
import java.io.Writer;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class SimpleProcess {
- /**
- * DOCUMENT ME!
- */
private static final Log LOG = LogFactory.getLog(SimpleProcess.class);
- /**
- * DOCUMENT ME!
- */
private File directory;
- /**
- * DOCUMENT ME!
- */
private String[] cmd;
- /**
- * DOCUMENT ME!
- */
private String stdout;
- /**
- * DOCUMENT ME!
- */
private String stderr;
-/**
+ /**
* Creates a new SimpleProcess object.
- *
- * @param aDirectory DOCUMENT ME!
- * @param aCmd DOCUMENT ME!
+ *
*/
public SimpleProcess(File aDirectory, String[] aCmd) {
- directory = aDirectory;
- cmd = aCmd;
+ directory = aDirectory;
+ cmd = aCmd;
}
/**
- * DOCUMENT ME!
- *
+ *
* @return the stdout
*/
public String getStdout() {
}
/**
- * DOCUMENT ME!
- *
+ *
* @return the stderr
*/
public String getStderr() {
/**
* Runs the process and blocks until it is done.
- *
+ *
* @return Exit status of the process.
- *
- * @throws IOException In case of problems.
+ *
+ * @throws IOException
+ * In case of problems.
*/
public int run() throws IOException {
return runImpl();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
private int runImpl() throws IOException {
try {
String fullcmd = "";
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 myStdout = new StringWriter();
- StringWriter myStderr = new StringWriter();
- Thread stdoutReader = readAndLogStream("STDOUT> ",
- proc.getInputStream(), myStdout);
- Thread stderrReader = readAndLogStream("STDERR> ",
- proc.getErrorStream(), myStderr);
+ StringWriter myStdout = new StringWriter();
+ StringWriter myStderr = new StringWriter();
+ Thread stdoutReader = readAndLogStream("STDOUT> ", proc
+ .getInputStream(), myStdout);
+ Thread stderrReader = readAndLogStream("STDERR> ", proc
+ .getErrorStream(), myStderr);
try {
proc.waitFor();
} catch (InterruptedException e) {
IOException exception = new IOException(
- "Process was terminated: " + this);
+ "Process was terminated: " + this);
exception.initCause(e);
throw exception;
}
waitForReader(stdoutReader);
waitForReader(stderrReader);
- stdout = myStdout.toString();
- stderr = myStderr.toString();
+ stdout = myStdout.toString();
+ stderr = myStderr.toString();
if (proc.exitValue() != 0) {
LOG.warn("Exit value was non-zero: " + this);
return proc.exitValue();
} catch (IOException e) {
- IOException exception = new IOException("Error executing process: "
- + this);
+ IOException exception = new IOException(
+ "Error executing process: " + this);
exception.initCause(e);
throw exception;
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aReaderThread DOCUMENT ME!
- */
private void waitForReader(Thread aReaderThread) {
try {
aReaderThread.join();
} catch (InterruptedException e) {
- LOG.warn(this
- + ": error waiting for output stream reader of process to finish");
+ LOG
+ .warn(this +
+ ": error waiting for output stream reader of process to finish");
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aPrefix DOCUMENT ME!
- * @param aStream DOCUMENT ME!
- * @param aOutput DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private Thread readAndLogStream(final String aPrefix,
final InputStream aStream, final Writer aOutput) {
Thread inputReader = new Thread() {
- @Override
- public void run() {
- BufferedReader br = null;
+ @Override
+ public void run() {
+ BufferedReader br = null;
- try {
- br = new BufferedReader(new InputStreamReader(aStream));
+ try {
+ br = new BufferedReader(new InputStreamReader(aStream));
- String str;
+ String str;
- while ((str = br.readLine()) != null) {
- LOG.debug(aPrefix + str);
- aOutput.write(str);
- }
- } catch (IOException e) {
- LOG.warn(SimpleProcess.this
- + ": error reading input stream", e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- LOG.warn("Error closing stream " + aPrefix);
- }
+ while ((str = br.readLine()) != null) {
+ LOG.debug(aPrefix + str);
+ aOutput.write(str);
+ }
+ } catch (IOException e) {
+ LOG.warn(SimpleProcess.this +
+ ": error reading input stream", e);
+ } finally {
+ if (br != null) {
+ try {
+ br.close();
+ } catch (IOException e) {
+ LOG.warn("Error closing stream " + aPrefix);
}
}
}
- };
+ }
+ };
inputReader.start();
return inputReader;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
String fullcmd = "";
import java.io.IOException;
import java.io.InputStream;
-
/**
* Input resource based on an input stream.
- *
+ *
* @author Erik Brakkee
*/
public class StreamResource implements InputResource {
*/
private InputStream stream;
-/**
+ /**
* Constructs a resource.
- *
+ *
* @param aStream
* Input stream to read.
*/
/*
* (non-Javadoc)
- *
+ *
* @see InputResource#getInputStream()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
public InputStream getInputStream() throws IOException {
return stream;
}
*/
package org.wamblee.observer;
-
/**
* Default observer notifier which calls
* {@link org.wamblee.observer.Observer#send(ObservableType, Event)}
* immediately.
- *
+ *
* @author Erik Brakkee
*/
-public class DefaultObserverNotifier<ObservableType, Event>
- implements ObserverNotifier<ObservableType, Event> {
+public class DefaultObserverNotifier<ObservableType, Event> implements
+ ObserverNotifier<ObservableType, Event> {
/**
* Constructs the notifier.
- *
+ *
*/
public DefaultObserverNotifier() {
// Empty
/*
* (non-Javadoc)
- *
- * @see org.wamblee.observer.ObserverNotifier#update(org.wamblee.observer.Observer,
- * ObservableType, Event)
+ *
+ * @see
+ * org.wamblee.observer.ObserverNotifier#update(org.wamblee.observer.Observer
+ * , ObservableType, Event)
*/
public void update(Observer<ObservableType, Event> aObserver,
ObservableType aObservable, Event aEvent) {
import java.util.Map;
import java.util.TreeMap;
-
/**
* Implements subscription and notification logic for an observer pattern. This
* class is thread safe.
/**
* Constructs the observable.
- *
+ *
* @param aObservable
* Observable this instance is used for.
* @param aNotifier
/**
* Subscribe an obvers.
- *
+ *
* @param aObserver
* Observer to subscribe.
* @return Event Event to send.
*/
- public synchronized long subscribe(
- Observer<ObservableType, Event> aObserver) {
+ public synchronized long subscribe(Observer<ObservableType, Event> aObserver) {
long subscription = counter++; // integer rage is so large it will
- // never roll over.
+ // never roll over.
observers.put(subscription, aObserver);
/**
* Unsubscribe an observer.
- *
+ *
* @param aSubscription
* Subscription which is used
* @throws IllegalArgumentException
/**
* Gets the number of subscribed observers.
- *
+ *
* @return Number of subscribed observers.
*/
public int getObserverCount() {
/**
* Notifies all subscribed observers.
- *
+ *
* @param aEvent
* Event to send.
*/
/*
* (non-Javadoc)
- *
+ *
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
if (observers.size() > 0) {
- LOGGER.error(
- "Still observers registered at finalization of observer!");
+ LOGGER
+ .error("Still observers registered at finalization of observer!");
for (Observer observer : observers.values()) {
LOGGER.error(" observer: " + observer);
*/
package org.wamblee.observer;
-
/**
* This is a type-safe version of {@link java.util.Observable}.
- *
+ *
* @author Erik Brakkee
*/
public interface Observer<ObservableType, Event> {
/**
* Called when an event has occurred on the observable.
- * @param aObservable Observable.
- * @param aEvent Event.
+ *
+ * @param aObservable
+ * Observable.
+ * @param aEvent
+ * Event.
*/
void send(ObservableType aObservable, Event aEvent);
}
*/
package org.wamblee.observer;
-
/**
* Implementation of notification of subscribers.
- *
+ *
* @author Erik Brakkee
*/
public interface ObserverNotifier<ObservableType, Event> {
/**
* Notifies an observer.
- *
- * @param aObserver Observer to notify
- * @param aObservable Observable at which the event occured.
- * @param aEvent Event that occured.
+ *
+ * @param aObserver
+ * Observer to notify
+ * @param aObservable
+ * Observable at which the event occured.
+ * @param aEvent
+ * Event that occured.
*/
void update(Observer<ObservableType, Event> aObserver,
ObservableType aObservable, Event aEvent);
import java.io.Serializable;
-
/**
* Default implementation of Persistent.
- *
+ *
* @author Erik Brakkee
*/
public abstract class AbstractPersistent implements Persistent {
*/
private int version;
-/**
+ /**
* Constructs the object.
- *
+ *
*/
protected AbstractPersistent() {
- primaryKey = null;
- version = -1;
+ primaryKey = null;
+ version = -1;
}
-/**
+ /**
* Copy constructor.
- * @param aPersistent Object to copy.
+ *
+ * @param aPersistent
+ * Object to copy.
*/
protected AbstractPersistent(AbstractPersistent aPersistent) {
- primaryKey = aPersistent.primaryKey;
- version = aPersistent.version;
+ primaryKey = aPersistent.primaryKey;
+ version = aPersistent.version;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.persistence.Persistent#getPrimaryKey()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Serializable getPrimaryKey() {
return primaryKey;
}
- /* (non-Javadoc)
- * @see org.wamblee.persistence.Persistent#setPrimaryKey(java.io.Serializable)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.wamblee.persistence.Persistent#setPrimaryKey(java.io.Serializable)
*/
public void setPrimaryKey(Serializable aKey) {
primaryKey = aKey;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.persistence.Persistent#getPersistedVersion()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public int getPersistedVersion() {
return version;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.persistence.Persistent#setPersistedVersion(int)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aVersion DOCUMENT ME!
- */
public void setPersistedVersion(int aVersion) {
version = aVersion;
}
import java.io.Serializable;
-
/**
- * Interface for persistent objects. This defines required functionality for all objects
- * that are persisted.
- *
+ * Interface for persistent objects. This defines required functionality for all
+ * objects that are persisted.
+ *
* Objects that implement this interface and which implement
- * {@link java.lang.Object#equals(java.lang.Object)}
- * should exclude the primary key and version from determining equality.
+ * {@link java.lang.Object#equals(java.lang.Object)} should exclude the primary
+ * key and version from determining equality.
*/
public interface Persistent {
/**
* Gets the primary key.
- *
+ *
* @return Primary key.
- *
+ *
* @see #setPrimaryKey(Serializable)
*/
Serializable getPrimaryKey();
/**
* Sets the primary key.
- *
- * @param aKey Primary key.
- *
+ *
+ * @param aKey
+ * Primary key.
+ *
* @see #getPrimaryKey()
*/
void setPrimaryKey(Serializable aKey);
/**
* Gets the version.
- *
+ *
* @return Version.
- *
+ *
* @see #setPersistedVersion(int)
*/
int getPersistedVersion();
/**
* Sets the version.
- *
- * @param aVersion Version.
- *
+ *
+ * @param aVersion
+ * Version.
+ *
* @see #getPersistedVersion()
*/
void setPersistedVersion(int aVersion);
import java.util.List;
import java.util.Map;
-
public class ReflectionUtils {
/**
- * Wraps a type by the corresponding wrapper type if it is a primitive
- * type.
- * @param aClass Type to wrap.
+ * Wraps a type by the corresponding wrapper type if it is a primitive type.
+ *
+ * @param aClass
+ * Type to wrap.
* @return Wrapped type for primitives or the provided argument value.
*/
public static Class wrapIfNeeded(Class aClass) {
aFound.put(method.getName(), method);
} else {
// super class method. Check for override.
- if (!Arrays.equals(superMethod.getParameterTypes(),
- method.getParameterTypes())) {
+ if (!Arrays.equals(superMethod.getParameterTypes(), method
+ .getParameterTypes())) {
// parameters differ so this is a new method.
aFound.put(method.getName(), method);
}
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
-
/**
* URI resolver that resolves stylesheets through the classpath.
*/
public class ClasspathUriResolver implements URIResolver {
-/**
+ /**
* Constructs the resolver.
- *
+ *
*/
public ClasspathUriResolver() {
// Empty.
/*
* (non-Javadoc)
- *
+ *
* @see javax.xml.transform.URIResolver#resolve(java.lang.String,
- * java.lang.String)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aHref DOCUMENT ME!
- * @param aBase DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws TransformerException DOCUMENT ME!
+ * java.lang.String)
*/
public Source resolve(String aHref, String aBase)
throws TransformerException {
return new StreamSource(xslt.getInputStream());
} catch (IOException e) {
throw new TransformerException(
- "Could not get XSLT style sheet in classpath '" + aHref + "'", e);
+ "Could not get XSLT style sheet in classpath '" + aHref + "'",
+ e);
}
}
}
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
-
/**
* Some basic XML utilities for common reoccuring tasks for DOM documents.
- *
+ *
* @author Erik Brakkee
*/
public final class DomUtils {
- /**
- * DOCUMENT ME!
- */
private static final Log LOG = LogFactory.getLog(DomUtils.class);
-/**
+ /**
* Disabled default constructor.
- *
+ *
*/
private DomUtils() {
// Empty.
/**
* Parses an XML document from a string.
- *
- * @param aDocument document.
- *
+ *
+ * @param aDocument
+ * document.
+ *
* @return
- *
- * @throws XMLException DOCUMENT ME!
+ *
*/
public static Document read(String aDocument) throws XMLException {
ByteArrayInputStream is = new ByteArrayInputStream(aDocument.getBytes());
/**
* Parses an XML document from a stream.
- *
- * @param aIs Input stream.
- *
+ *
+ * @param aIs
+ * Input stream.
+ *
* @return
- *
- * @throws XMLException DOCUMENT ME!
+ *
*/
public static Document read(InputStream aIs) throws XMLException {
try {
/**
* Reads and validates a document against a schema.
- *
- * @param aIs Input stream.
- * @param aSchema Schema.
- *
+ *
+ * @param aIs
+ * Input stream.
+ * @param aSchema
+ * Schema.
+ *
* @return Parsed and validated document.
- *
- * @throws XMLException DOCUMENT ME!
+ *
*/
public static Document readAndValidate(InputStream aIs, InputStream aSchema)
throws XMLException {
try {
- final Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
- .newSchema(new StreamSource(aSchema));
+ final Schema schema = SchemaFactory.newInstance(
+ XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
+ new StreamSource(aSchema));
final DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
/**
* Serializes an XML document to a stream.
- *
- * @param aDocument Document to serialize.
- * @param aOs Output stream.
- *
- * @throws IOException DOCUMENT ME!
+ *
+ * @param aDocument
+ * Document to serialize.
+ * @param aOs
+ * Output stream.
+ *
*/
public static void serialize(Document aDocument, OutputStream aOs)
throws IOException {
/**
* Serializes an XML document.
- *
- * @param aDocument Document to serialize.
- *
+ *
+ * @param aDocument
+ * Document to serialize.
+ *
* @return Serialized document.
- *
- * @throws IOException DOCUMENT ME!
+ *
*/
- public static String serialize(Document aDocument)
- throws IOException {
+ public static String serialize(Document aDocument) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
serialize(aDocument, os);
/**
* Converts a dom4j document into a w3c DOM document.
- *
- * @param aDocument Document to convert.
- *
+ *
+ * @param aDocument
+ * Document to convert.
+ *
* @return W3C DOM document.
- *
- * @throws DocumentException DOCUMENT ME!
+ *
*/
public static Document convert(org.dom4j.Document aDocument)
throws DocumentException {
/**
* Converts a W3C DOM document into a dom4j document.
- *
- * @param aDocument Document to convert.
- *
+ *
+ * @param aDocument
+ * Document to convert.
+ *
* @return Dom4j document.
*/
public static org.dom4j.Document convert(Document aDocument) {
/**
* Removes duplicate attributes from a DOM tree.This is useful for
* postprocessing the output of JTidy as a workaround for a bug in JTidy.
- *
- * @param aNode Node to remove duplicate attributes from (recursively).
- * Attributes of the node itself are not dealt with. Only the child
- * nodes are dealt with.
+ *
+ * @param aNode
+ * Node to remove duplicate attributes from (recursively).
+ * Attributes of the node itself are not dealt with. Only the
+ * child nodes are dealt with.
*/
public static void removeDuplicateAttributes(Node aNode) {
NodeList list = aNode.getChildNodes();
/**
* Removes duplicate attributes from an element.
- *
- * @param aElement Element.
+ *
+ * @param aElement
+ * Element.
*/
private static void removeDuplicateAttributes(Element aElement) {
- NamedNodeMap attributes = aElement.getAttributes();
+ NamedNodeMap attributes = aElement.getAttributes();
Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
- List<Attr> attlist = new ArrayList<Attr>();
+ List<Attr> attlist = new ArrayList<Attr>();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attribute = (Attr) attributes.item(i);
if (uniqueAttributes.containsKey(attribute.getNodeName())) {
- LOG.info("Detected duplicate attribute (will be removed)'"
- + attribute.getNodeName() + "'");
+ LOG.info("Detected duplicate attribute (will be removed)'" +
+ attribute.getNodeName() + "'");
}
uniqueAttributes.put(attribute.getNodeName(), attribute);
/**
* Exception thrown in case of XML parsing problems.
- *
+ *
* @author Erik Brakkee
*/
public class XMLException extends Exception {
-/**
+ /**
* Creates a new XMLException object.
- *
- * @param aMsg DOCUMENT ME!
+ *
*/
public XMLException(String aMsg) {
super(aMsg);
}
-/**
+ /**
* Creates a new XMLException object.
- *
- * @param aMsg DOCUMENT ME!
- * @param aCause DOCUMENT ME!
+ *
*/
public XMLException(String aMsg, Throwable aCause) {
super(aMsg, aCause);
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
-
/**
* XSL transformer for simplified usage of XSL transformations.
- *
+ *
* @author Erik Brakkee
*/
public class XslTransformer {
- /**
- * DOCUMENT ME!
- */
private TransformerFactory factory;
-/**
+ /**
* Constructs the URL resolver.
- *
+ *
* @param aResolver
* URI resolver to use.
*/
factory.setURIResolver(aResolver);
}
-/**
+ /**
* Constructs the XSLT processor.
- *
+ *
*/
public XslTransformer() {
factory = TransformerFactory.newInstance();
/**
* Resolves an XSLT based on URI.
- *
- * @param aXslt XSLT to resolve,
- *
+ *
+ * @param aXslt
+ * XSLT to resolve,
+ *
* @return Source for the XSLT
- *
- * @throws TransformerException In case the XSLT cannot be found.
+ *
+ * @throws TransformerException
+ * In case the XSLT cannot be found.
*/
public Source resolve(String aXslt) throws TransformerException {
URIResolver resolver = factory.getURIResolver();
}
/**
- * Transforms a DOM document into another DOM document using a
- * given XSLT transformation.
- *
- * @param aDocument Document to transform.
- * @param aXslt XSLT to use.
- *
+ * Transforms a DOM document into another DOM document using a given XSLT
+ * transformation.
+ *
+ * @param aDocument
+ * Document to transform.
+ * @param aXslt
+ * XSLT to use.
+ *
* @return Transformed document.
- *
- * @throws IOException In case of problems reading resources.
- * @throws TransformerException In case transformation fails.
+ *
+ * @throws IOException
+ * In case of problems reading resources.
+ * @throws TransformerException
+ * In case transformation fails.
*/
public Document transform(Document aDocument, Source aXslt)
throws IOException, TransformerException {
- Source source = new DOMSource(aDocument);
+ Source source = new DOMSource(aDocument);
DOMResult result = new DOMResult();
transform(source, result, aXslt);
/**
* Transforms a document using XSLT.
- *
- * @param aDocument Document to transform.
- * @param aXslt XSLT to use.
- *
+ *
+ * @param aDocument
+ * Document to transform.
+ * @param aXslt
+ * XSLT to use.
+ *
* @return Transformed document.
- *
- * @throws IOException In case of problems reading resources.
- * @throws TransformerException In case transformation fails.
+ *
+ * @throws IOException
+ * In case of problems reading resources.
+ * @throws TransformerException
+ * In case transformation fails.
*/
public Document transform(byte[] aDocument, Source aXslt)
throws IOException, TransformerException {
- Source source = new StreamSource(new ByteArrayInputStream(aDocument));
+ Source source = new StreamSource(new ByteArrayInputStream(aDocument));
DOMResult result = new DOMResult();
transform(source, result, aXslt);
/**
* Transforms a document to a text output. This supports XSLT
* transformations that result in text documents.
- *
- * @param aDocument Document to transform.
- * @param aXslt XSL transformation.
- *
+ *
+ * @param aDocument
+ * Document to transform.
+ * @param aXslt
+ * XSL transformation.
+ *
* @return Transformed document.
- *
- * @throws IOException DOCUMENT ME!
- * @throws TransformerException DOCUMENT ME!
+ *
*/
public String textTransform(byte[] aDocument, Source aXslt)
throws IOException, TransformerException {
- Source source = new StreamSource(new ByteArrayInputStream(
- aDocument));
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- StreamResult result = new StreamResult(os);
+ Source source = new StreamSource(new ByteArrayInputStream(aDocument));
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ StreamResult result = new StreamResult(os);
transform(source, result, aXslt);
return new String(os.toByteArray());
/**
* Transforms a document using XSLT.
- *
- * @param aSource Document to transform.
- * @param aResult Result of the transformation.
- * @param aXslt XSLT to use.
- *
- * @throws IOException In case of problems reading resources.
- * @throws TransformerException In case transformation fails.
+ *
+ * @param aSource
+ * Document to transform.
+ * @param aResult
+ * Result of the transformation.
+ * @param aXslt
+ * XSLT to use.
+ *
+ * @throws IOException
+ * In case of problems reading resources.
+ * @throws TransformerException
+ * In case transformation fails.
*/
public void transform(Source aSource, Result aResult, Source aXslt)
throws IOException, TransformerException {
Transformer transformer = factory.newTransformer(aXslt);
transformer.transform(aSource, aResult);
} catch (TransformerConfigurationException e) {
- throw new TransformerException("Configuration problem of XSLT transformation",
- e);
+ throw new TransformerException(
+ "Configuration problem of XSLT transformation", e);
}
}
}
import java.io.IOException;
-
/**
* Cached object test.
- *
+ *
* @author Erik Brakkee
*/
public class CachedObjectTest extends TestCase {
- /**
- *
- */
private static final String EHCACHE_CONFIG = "ehcache.xml";
private static final int OBJECT_KEY = 10;
private CachedObject.Computation<Integer, Integer> computation;
private int ncomputations;
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
super.setUp();
computation = new CachedObject.Computation<Integer, Integer>() {
- public Integer getObject(Integer aObjectKey) {
- ncomputations++;
+ public Integer getObject(Integer aObjectKey) {
+ ncomputations++;
- return compute(aObjectKey);
- }
- ;
- };
+ return compute(aObjectKey);
+ };
+ };
ncomputations = 0;
}
/**
* Verifies that upon first use, the cached object uses the computation to
* retrieve the object.
- *
+ *
*/
public void testComputation() {
CachedObject<Integer, Integer> cached = createCached(new ZeroCache<Integer, Integer>());
}
public void testBehaviorEhCache() throws CacheException, IOException {
- Cache<Integer, Integer> cache = new EhCache<Integer, Integer>(new TestResource(
- CachedObjectTest.class, EHCACHE_CONFIG), "test");
+ Cache<Integer, Integer> cache = new EhCache<Integer, Integer>(
+ new TestResource(CachedObjectTest.class, EHCACHE_CONFIG), "test");
CachedObject<Integer, Integer> cached = createCached(cache);
assertTrue(cache == cached.getCache());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(1, ncomputations);
- // The value must still be cached.
+ // The value must still be cached.
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(1, ncomputations);
- // Cache expiry.
+ // Cache expiry.
TimingUtils.sleep(6000);
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
}
public void testBehaviorEhCacheDefault() throws CacheException, IOException {
- Cache<Integer, Integer> cache = new EhCache<Integer, Integer>(new TestResource(
- CachedObjectTest.class, EHCACHE_CONFIG), "undefined");
+ Cache<Integer, Integer> cache = new EhCache<Integer, Integer>(
+ new TestResource(CachedObjectTest.class, EHCACHE_CONFIG),
+ "undefined");
CachedObject<Integer, Integer> cached = createCached(cache);
assertTrue(cache == cached.getCache());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(1, ncomputations);
- // The value must still be cached.
+ // The value must still be cached.
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(1, ncomputations);
- // Cache expiry.
+ // Cache expiry.
TimingUtils.sleep(6000);
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
import java.util.Arrays;
import java.util.List;
-
public class CollectionFilterTest extends TestCase {
public void testFilter() {
List<String> list = Arrays.asList(new String[] { "x", "y", "z", "y" });
List<String> result = new ArrayList<String>();
- CollectionFilter.filter(list, result,
- new Condition<String>() {
- @Override
- public boolean matches(String aObject) {
- return aObject.equals("y");
- }
- });
- AssertionUtils.assertEquals(new String[] { "y", "y" }, result.toArray());
+ CollectionFilter.filter(list, result, new Condition<String>() {
+ @Override
+ public boolean matches(String aObject) {
+ return aObject.equals("y");
+ }
+ });
+ AssertionUtils
+ .assertEquals(new String[] { "y", "y" }, result.toArray());
}
}
import org.wamblee.test.EventTracker;
import org.wamblee.test.TimingUtils;
-
/**
* Tests for the JVMLock.
- *
+ *
* @author Erik Brakkee
*/
public abstract class AbstractLockTestCase extends TestCase {
/*
* (non-Javadoc)
- *
+ *
* @see junit.framework.TestCase#setUp()
*/
@Override
}
/**
- * Must be implemented to generate the events
- * {@link #STARTED}, {@link #ACQUIRED}, and {@link #RELEASED} in
- * that order. The lock should be acquired for
- * the time specified by {@link #SLEEP_TIME}.
+ * Must be implemented to generate the events {@link #STARTED},
+ * {@link #ACQUIRED}, and {@link #RELEASED} in that order. The lock should
+ * be acquired for the time specified by {@link #SLEEP_TIME}.
+ *
* @return Thread which does the work.
*/
protected abstract Thread runThread();
Thread t1 = runThread();
Thread t2 = runThread();
TimingUtils.sleep(SLEEP_TIME / 10); // give threads a chance to start
- // up.
+ // up.
assertEquals(2, tracker.getEventCount(STARTED)); // both threads
- // should have
- // started.
+ // should have
+ // started.
assertEquals(1, tracker.getEventCount(ACQUIRED)); // one thread has
- // acquired the
- // lock.
+ // acquired the
+ // lock.
TimingUtils.sleep(SLEEP_TIME);
assertEquals(2, tracker.getEventCount(ACQUIRED)); // now the other
- // thread could also
- // acquire the lock
+ // thread could also
+ // acquire the lock
assertEquals(1, tracker.getEventCount(RELEASED)); // and the first
- // thread has
- // released it.
+ // thread has
+ // released it.
TimingUtils.sleep(SLEEP_TIME);
assertEquals(2, tracker.getEventCount(RELEASED)); // both threads
- // should be
- // finished.
+ // should be
+ // finished.
t1.join();
t2.join();
import org.wamblee.test.TimingUtils;
-
/**
* Tests for the JVMLock.
- *
+ *
* @author Erik Brakkee
*/
public class JvmLockTest extends AbstractLockTestCase {
/*
* (non-Javadoc)
- *
+ *
* @see junit.framework.TestCase#setUp()
*/
@Override
protected Thread runThread() {
Thread t = new Thread(new Runnable() {
- public void run() {
- getTracker().eventOccurred(STARTED);
- lock.acquire();
- getTracker().eventOccurred(ACQUIRED);
- TimingUtils.sleep(SLEEP_TIME);
- lock.release();
- getTracker().eventOccurred(RELEASED);
- }
- ;
- });
+ public void run() {
+ getTracker().eventOccurred(STARTED);
+ lock.acquire();
+ getTracker().eventOccurred(ACQUIRED);
+ TimingUtils.sleep(SLEEP_TIME);
+ lock.release();
+ getTracker().eventOccurred(RELEASED);
+ };
+ });
t.start();
return t;
import junit.framework.Assert;
import junit.framework.TestCase;
-
/**
* Testing the read-write lock class. Note: in case of problems, test cases
* could hang.
- *
+ *
* @see ReadWriteLock
*/
public class ReadWriteLockTest extends TestCase {
- /**
- *
- */
private static final int HALF_SECOND = 500;
- /**
- *
- */
private static final int ONE_SECOND = 1000;
- /**
- *
- */
private static final int TWO_SECONDS = 2000;
private ReadWriteLock lock;
private int nReaders;
/**
* Constructor for ReadWriteLockTest.
- *
+ *
* @param aName
*/
public ReadWriteLockTest(String aName) {
/**
* Verify concurrent access by multiple readers is possible.
- *
- * @throws InterruptedException May not occur.
+ *
+ * @throws InterruptedException
+ * May not occur.
*/
public void testMultipleReaders() throws InterruptedException {
Runnable runnable = new ReadLocker(lock, this, TWO_SECONDS);
/**
* Verify that only one writer at a time can acquire the write lock.
- *
- * @throws InterruptedException May not occur.
+ *
+ * @throws InterruptedException
+ * May not occur.
*/
public void testSingleWriter() throws InterruptedException {
WriteLocker writer = new WriteLocker(lock, this, ONE_SECOND);
/**
* Verify that multiple writers cannot acquire the write lock concurrently.
- *
- * @throws InterruptedException May not occur.
+ *
+ * @throws InterruptedException
+ * May not occur.
*/
public void testMultipleWriters() throws InterruptedException {
- WriteLocker writer1 = new WriteLocker(lock, this,
- HALF_SECOND + 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);
Thread.sleep(ONE_SECOND);
// at t = 2, the second writer still must have
- // a lock.
+ // a lock.
assertTrue(getWriterCount() == 1);
t1.join();
t2.join();
}
/**
- * Verify that after the first reader acquires a lock, a subsequent writer
+ * Verify that after the first reader acquires a lock, a subsequent writer
* can only acquire the lock after the reader has released it.
- *
- * @throws InterruptedException May not occur.
+ *
+ * @throws InterruptedException
+ * May not occur.
*/
public void testReadWrite1() throws InterruptedException {
ReadLocker readLocker = new ReadLocker(lock, this, TWO_SECONDS);
Thread.sleep(HALF_SECOND);
// 1 second underway, reader still holding the
- // lock so write lock cannot be acquired.
+ // lock so write lock cannot be acquired.
assertTrue(getReaderCount() == 1);
assertTrue(getWriterCount() == 0);
Thread.sleep(ONE_SECOND + HALF_SECOND);
- // 2.5 seconds underway, read lock released and
- // write lock must be acquired.
+ // 2.5 seconds underway, read lock released and
+ // write lock must be acquired.
assertTrue("Wrong no. of readers: " + getReaderCount(),
getReaderCount() == 0);
assertTrue(getWriterCount() == 1);
/**
* Verify that when multiple readers have acquired a read lock, the writer
* can only acquire the lock after all readers have released it.
- *
- * @throws InterruptedException May not occur.
+ *
+ * @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);
Thread.sleep(HALF_SECOND);
// t = 1.5
assertTrue(getReaderCount() == 2);
- t3.start(); // write lock
+ t3.start(); // write lock
Thread.sleep(HALF_SECOND);
- // 2 seconds,
+ // 2 seconds,
assertTrue(getReaderCount() == 2);
assertTrue(getWriterCount() == 0);
Thread.sleep(ONE_SECOND);
assertTrue(getWriterCount() == 0);
Thread.sleep(ONE_SECOND);
- // 4 seconds underway, write lock must have
- // been acquired.
+ // 4 seconds underway, write lock must have
+ // been acquired.
assertTrue(getReaderCount() == 0);
assertTrue(getWriterCount() == 1);
}
/**
- * Verify that after a writer acquires a lock, a subsequent reader can
- * only acquire the lock after the writer has released it.
- *
- * @throws InterruptedException May not occur.
+ * Verify that after a writer acquires a lock, a subsequent reader can only
+ * acquire the lock after the writer has released it.
+ *
+ * @throws InterruptedException
+ * May not occur.
*/
public void testReadWrite3() throws InterruptedException {
ReadLocker readLocker = new ReadLocker(lock, this, TWO_SECONDS);
Thread.sleep(HALF_SECOND);
// 1 second underway, writer still holding the
- // lock so read lock cannot be acquired.
+ // lock so read lock cannot be acquired.
assertTrue(getWriterCount() == 1);
assertTrue(getReaderCount() == 0);
Thread.sleep(ONE_SECOND + HALF_SECOND);
- // 2.5 seconds underway, write lock released and
- // read lock must be acquired.
+ // 2.5 seconds underway, write lock released and
+ // read lock must be acquired.
assertTrue("Wrong no. of writers: " + getReaderCount(),
getWriterCount() == 0);
assertTrue(getReaderCount() == 1);
}
/*
- * The following test cases are for testing whether or not
- * the read write lock checks the locking correctly.
- * Strictly speaking, these checks wouldn't be necessary
- * because it involves the contract of the ReadWriteLock which
- * must be obeyed by users of the ReadWriteLock. Nevertheless,
- * this is tested anyway to be absolutely sure.
+ * The following test cases are for testing whether or not the read write
+ * lock checks the locking correctly. Strictly speaking, these checks
+ * wouldn't be necessary because it involves the contract of the
+ * ReadWriteLock which must be obeyed by users of the ReadWriteLock.
+ * Nevertheless, this is tested anyway to be absolutely sure.
*/
/**
- * Acquire a read lock from one thread, release it from another. Verify
- * that a RuntimeException is thrown.
- *
- * @throws InterruptedException May not occur.
+ * Acquire a read lock from one thread, release it from another. Verify that
+ * a RuntimeException is thrown.
+ *
+ * @throws InterruptedException
+ * May not occur.
*/
public void testReleaseReadFromWrongThread() throws InterruptedException {
Thread t1 = null;
try {
t1 = new Thread(new Runnable() {
- public void run() {
- ReadWriteLockTest.this.lock.acquireRead();
- }
- });
+ public void run() {
+ ReadWriteLockTest.this.lock.acquireRead();
+ }
+ });
t1.start();
Thread.sleep(ONE_SECOND); // wait until thread is started
lock.releaseRead(); // release lock from wrong thread.
/**
* Acquire a write lock from one thread, release it from another. Verify
* that a RuntimeException is thrown.
- *
- * @throws InterruptedException May not occur.
+ *
+ * @throws InterruptedException
+ * May not occur.
*/
public void testReleaseWriteFromWrongThread() throws InterruptedException {
Thread t1 = null;
try {
t1 = new Thread(new Runnable() {
- public void run() {
- ReadWriteLockTest.this.lock.acquireWrite();
- }
- });
+ public void run() {
+ ReadWriteLockTest.this.lock.acquireWrite();
+ }
+ });
t1.start();
Thread.sleep(ONE_SECOND); // wait until thread is started
lock.releaseWrite(); // release lock from wrong thread.
}
/**
- * Try to acquire a read lock multiple times. Verify that a
- * RuntimeException is thrown.
+ * Try to acquire a read lock multiple times. Verify that a RuntimeException
+ * is thrown.
*/
public void testAcquireReadTwice() {
try {
}
}
-
/**
- * ReadLocker acquires a read lock and performs a callback when the lock as
- * been acquired, sleeps for a designated amount of time, releases the read
- * lock, and performs a callback after the lock has been released.
+ * ReadLocker acquires a read lock and performs a callback when the lock as been
+ * acquired, sleeps for a designated amount of time, releases the read lock, and
+ * performs a callback after the lock has been released.
*/
class ReadLocker implements Runnable {
private ReadWriteLock lock;
}
}
-
/**
- * WriteLocker acquires a write lock and performs a callback when the lock as
+ * WriteLocker acquires a write lock and performs a callback when the lock as
* been acquired, sleeps for a designated amount of time, releases the write
* lock, and performs a callback after the lock has been released.
*/
import java.util.ArrayList;
import java.util.List;
-
/**
* Tests the Or Condition.
- *
+ *
* @author Erik Brakkee
*/
public class AndConditionTest extends TestCase {
public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) {
- AndCondition<Integer> and = new AndCondition<Integer>(new FixedCondition<Integer>(
- aFirst), new FixedCondition<Integer>(aSecond));
+ AndCondition<Integer> and = new AndCondition<Integer>(
+ new FixedCondition<Integer>(aFirst), new FixedCondition<Integer>(
+ aSecond));
assertEquals(aResult, and.matches(0));
}
/**
* Checks all combinations of two conditions.
- *
+ *
*/
public void testTwoConditions() {
checkResult(false, false, false);
*/
package org.wamblee.conditions;
-
/**
* Test condition object.
- *
+ *
* @author Erik Brakkee
*/
public class GreaterThanCondition implements Condition<Integer> {
value = aValue;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.conditions.Condition#matches(T)
*/
public boolean matches(Integer aObject) {
*/
package org.wamblee.conditions;
-
/**
* Test condition object.
- *
+ *
* @author Erik Brakkee
*/
public class LessThanCondition implements Condition<Integer> {
value = aValue;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.conditions.Condition#matches(T)
*/
public boolean matches(Integer aObject) {
import java.util.ArrayList;
import java.util.List;
-
/**
* Tests the Or Condition.
- *
+ *
* @author Erik Brakkee
*/
public class OrConditionTest extends TestCase {
public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) {
- OrCondition<Integer> or = new OrCondition<Integer>(new FixedCondition<Integer>(
- aFirst), new FixedCondition<Integer>(aSecond));
+ OrCondition<Integer> or = new OrCondition<Integer>(
+ new FixedCondition<Integer>(aFirst), new FixedCondition<Integer>(
+ aSecond));
assertEquals(aResult, or.matches(0));
}
/**
* Checks all combinations of two conditions.
- *
+ *
*/
public void testTwoConditions() {
checkResult(false, false, false);
import junit.framework.TestCase;
-
/**
* Tests {@link org.wamblee.conditions.PropertyRegexCondition}.
- *
+ *
* @author Erik Brakkee
*/
public class PropertyRegexConditionTest extends TestCase {
private boolean match(String aProperty, String aRegex, boolean aToLower,
TestBean aBean) {
- PropertyRegexCondition<TestBean> condition = new PropertyRegexCondition<TestBean>(aProperty,
- aRegex, aToLower);
+ PropertyRegexCondition<TestBean> condition = new PropertyRegexCondition<TestBean>(
+ aProperty, aRegex, aToLower);
return condition.matches(aBean);
}
/**
* Verifies correct matching behavior for several cases.
- *
+ *
*/
public void testMatchProperty() {
TestBean bean = new TestBean("Hallo");
checkMatch("value", "Hallo", false, bean, true);
checkMatch("value", "all", false, bean, false);
checkMatch("value", ".a.*o", false, bean, true);
- checkMatch("value", "hallo", false, bean, false); // no match when not converting to lower case.
+ checkMatch("value", "hallo", false, bean, false); // no match when not
+ // converting to lower
+ // case.
checkMatch("value", "hallo", true, bean, true); // match!
}
/**
- * Uses property regex condition for non-existing property.
- * Verifies that a runtime exception is thrown.
- *
+ * Uses property regex condition for non-existing property. Verifies that a
+ * runtime exception is thrown.
+ *
*/
public void testWrongProperty() {
TestBean bean = new TestBean("Hallo");
/**
* Applies condition to a private property. Verifies that a runtime
* exception is thrown.
- *
+ *
*/
public void testPrivateProperty() {
TestBean bean = new TestBean("Hallo");
*/
package org.wamblee.conditions;
-
/**
- *
- *
+ *
+ *
* @author Erik Brakkee
*/
public class TestBean {
import junit.framework.TestCase;
-
/**
* Tests the bean kernel. The lookup of the bean factory itself can be tested
* only partially. Using a global property file for all test cases would tie all
* test cases together therefore no global property file is used.
- *
+ *
* @author Erik Brakkee
*/
public class BeanKernelTest extends TestCase {
/**
* Loads the bean factory based on a property file configuration. Verifies
* the correct bean factory is loaded.
- *
+ *
*/
public void testLoadBeanFactoryFromProperties() {
- BeanFactory factory = BeanKernel.lookupBeanFactory(
- "org/wamblee/general/beankernel.properties");
+ BeanFactory factory = BeanKernel
+ .lookupBeanFactory("org/wamblee/general/beankernel.properties");
assertTrue(factory instanceof TestBeanFactory);
}
/**
- * Loads the bean factory based on a non-existing property file.
- * Verifies that BeanFactoryException is thrown.
- *
+ * Loads the bean factory based on a non-existing property file. Verifies
+ * that BeanFactoryException is thrown.
+ *
*/
public void testNonExistentPropertyFile() {
try {
- BeanKernel.lookupBeanFactory(
- "org/wamblee/general/beankernel-nonexistent.properties");
+ BeanKernel
+ .lookupBeanFactory("org/wamblee/general/beankernel-nonexistent.properties");
} catch (BeanFactoryException e) {
return; // ok
}
}
/**
- * Loads the bean factory based on a property file with a non-existing
- * bean factory defined in it.
- * Verifies that BeanFactoryException is thrown.
- *
+ * Loads the bean factory based on a property file with a non-existing bean
+ * factory defined in it. Verifies that BeanFactoryException is thrown.
+ *
*/
public void testNonExistentBeanFactory() {
try {
- BeanKernel.lookupBeanFactory(
- "org/wamblee/general/beankernel-wrong.properties");
+ BeanKernel
+ .lookupBeanFactory("org/wamblee/general/beankernel-wrong.properties");
} catch (BeanFactoryException e) {
return; // ok
}
/**
* Retrieves a bean factory throug the bean kernel. Verifies that beans can
* be retrieved.
- *
+ *
*/
public void testRetrieveFactory() {
BeanKernel.overrideBeanFactory(new TestBeanFactory()); // bypass
- // default
- // property
- // lookup
+ // default
+ // property
+ // lookup
BeanFactory factory = BeanKernel.getBeanFactory();
assertNotNull(factory);
import junit.framework.TestCase;
-
/**
* Tests the pair class.
*/
import java.io.IOException;
import java.io.InputStream;
-
/**
* Tests for the classpath resource.
*/
public class ClassPathResourceTest extends TestCase {
/**
* Loads an existing resource from the class path. Verifies it is found.
- *
+ *
*/
public void testResourceFound() throws IOException {
ClassPathResource resource = new ClassPathResource(
- "org/wamblee/io/myresource.txt");
+ "org/wamblee/io/myresource.txt");
InputStream is = resource.getInputStream();
String data = FileSystemUtils.read(is);
assertEquals("This is my resource", data);
/**
* Loads a non-existing resource from the class path. Verifies that an IO
* exception is thrown.
- *
+ *
*/
public void testResourceNotFound() {
try {
ClassPathResource resource = new ClassPathResource(
- "org/wamblee/io/myresource-nonexistent.txt");
+ "org/wamblee/io/myresource-nonexistent.txt");
InputStream is = resource.getInputStream();
} catch (IOException e) {
return; // ok
import org.apache.oro.io.AwkFilenameFilter;
import static org.mockito.Mockito.*;
+
public class DirectoryMonitorTest extends TestCase {
private static final String REGEX = "^.*\\.txt$";
private static final String FILE1 = "file1.txt";
data = new TestData(this);
data.clean();
listener = mock(DirectoryMonitor.Listener.class);
- monitor = new DirectoryMonitor(data.getRoot(),
- new AwkFilenameFilter(REGEX), listener);
+ monitor = new DirectoryMonitor(data.getRoot(), new AwkFilenameFilter(
+ REGEX), listener);
}
public void testEmptyDir() {
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();
import java.io.File;
-
/**
- *
- *
+ *
+ *
* @author Erik Brakkee
*/
public class DirectoryMonitorTestProgram {
public static void main(String[] aArgs) throws Exception {
DirectoryMonitor monitor = new DirectoryMonitor(new File("."),
- new AwkFilenameFilter(".*\\.txt"),
- new DirectoryMonitor.Listener() {
- public void fileChanged(File aFile) {
- System.out.println("changed " + aFile);
- }
+ new AwkFilenameFilter(".*\\.txt"), new DirectoryMonitor.Listener() {
+ public void fileChanged(File aFile) {
+ System.out.println("changed " + aFile);
+ }
- public void fileCreated(File aFile) {
- System.out.println("created " + aFile);
- }
+ public void fileCreated(File aFile) {
+ System.out.println("created " + aFile);
+ }
- public void fileDeleted(File aFile) {
- System.out.println("deleted " + aFile);
- }
- });
+ public void fileDeleted(File aFile) {
+ System.out.println("deleted " + aFile);
+ }
+ });
for (;;) {
monitor.poll();
import java.io.IOException;
import java.io.InputStream;
-
/**
* Tests the file resource.
- *
+ *
* @author Erik Brakkee
*/
public class FileResourceTest extends TestCase {
/**
* Loads an existing resource. Verifies it is found.
- *
+ *
*/
public void testResourceFound() throws IOException {
- FileResource resource = new FileResource(new File(
- FileSystemUtils.getTestInputDir(FileResourceTest.class),
- "myresource.txt"));
+ FileResource resource = new FileResource(new File(FileSystemUtils
+ .getTestInputDir(FileResourceTest.class), "myresource.txt"));
InputStream is = resource.getInputStream();
String data = FileSystemUtils.read(is);
assertEquals("This is my resource", data);
}
/**
- * Loads a non-existing resource. Verifies that an IO
- * exception is thrown.
- *
+ * Loads a non-existing resource. Verifies that an IO exception is thrown.
+ *
*/
public void testResourceNotFound() {
try {
- FileResource resource = new FileResource(new File(
- FileSystemUtils.getTestInputDir(FileResourceTest.class),
- "myresource-nonexistent.txt"));
+ FileResource resource = new FileResource(new File(FileSystemUtils
+ .getTestInputDir(FileResourceTest.class),
+ "myresource-nonexistent.txt"));
InputStream is = resource.getInputStream();
} catch (IOException e) {
return; // ok
import java.security.CodeSource;
-
/**
* File system utilities.
- *
+ *
* @author Erik Brakkee
*/
public final class FileSystemUtils {
/*
* Disabled.
- *
*/
private FileSystemUtils() {
// Empty
/**
* Deletes a directory recursively. The test case will fail if the directory
* does not exist or if deletion fails.
- *
+ *
* @param aDir
* Directory to delete.
*/
/**
* Deletes a directory recursively. See {@link #deleteDirRecursively}.
- *
+ *
* @param aDir
* Directory.
*/
* Deletes a file or directory. The test case will fail if the file or
* directory does not exist or if deletion fails. Deletion of a non-empty
* directory will always fail.
- *
+ *
* @param aFile
* File or directory to delete.
*/
* Gets a path relative to a sub project. This utility should be used to
* easily access file paths within a subproject without requiring any
* specific Eclipse configuration.
- *
+ *
* @param aRelativePath
* Relative path.
* @param aTestClass
/**
* Ensures that a directory hierarchy exists (recursively if needed). If it
* is not possible to create the directory, then the test case will fail.
- *
+ *
* @param aDir
* Directory to create.
*/
/**
* Creates a file in a directory.
- * @param aDir Directory path. Will be created if it does not exist.
- * @param aName Filename.
- * @param aContents Contents.
+ *
+ * @param aDir
+ * Directory path. Will be created if it does not exist.
+ * @param aName
+ * Filename.
+ * @param aContents
+ * Contents.
*/
public static void createFile(File aDir, String aName, InputStream aContents) {
createDir(aDir);
/**
* Gets the test output directory for a specific test class.
- *
+ *
* @param aTestClass
* Test class.
* @return Test output directory.
/**
* Gets the test input directory for a specific test class.
- *
+ *
* @param aTestClass
* Test class.
* @return Test input directory.
/**
* Creates a directory hierarchy for the output directory of a test class if
* needed.
- *
+ *
* @param aTestClass
* Test class
* @return Test directory.
* Gets a test output file name. This returns a File object representing the
* output file and ensures that the directory where the file will be created
* already exists.
- *
+ *
* @param aName
* Name of the file.
* @param aTestClass
/**
* Copies an input stream to an output stream.
- *
+ *
* @param aIs
* Input stream.
* @param aOs
/**
* Recursively copy a directory.
- *
+ *
* @param aSrc
* Source directory
* @param aTarget
if (file.isDirectory()) {
if (!file.getName().equals(".svn")) {
- copyDir(new File(aSrc, file.getName()),
- new File(aTarget, file.getName()));
+ copyDir(new File(aSrc, file.getName()), new File(aTarget,
+ file.getName()));
}
} else {
copyFile(file, new File(aTarget, file.getName()));
/**
* Copy a file. If copying fails then the testcase will fail.
- *
+ *
* @param aSrc
* Source file.
* @param aTarget
// map input file
MappedByteBuffer mbb = fcin.map(FileChannel.MapMode.READ_ONLY, 0,
- fcin.size());
+ fcin.size());
// do the file copy
fcout.write(mbb);
* This only attempts to remove regular files and not directories within the
* directory. If the directory contains a nested directory, the deletion
* will fail. The test case will fail if this fails.
- *
+ *
* @param aDir
* Directory to remove.
*/
/**
* Remove all regular files within a given directory.
- *
+ *
* @param outputDirName
*/
public static void cleanDir(File aDir) {
import java.io.IOException;
import java.io.InputStream;
-
/**
* Tests the stream resource.
- *
+ *
* @author Erik Brakkee
*/
public class StreamResourceTest extends TestCase {
/**
* Loads an existing resource. Verifies it is found.
- *
+ *
*/
public void testResourceFound() throws IOException {
- File file = new File(FileSystemUtils.getTestInputDir(
- StreamResourceTest.class), "myresource.txt");
+ File file = new File(FileSystemUtils
+ .getTestInputDir(StreamResourceTest.class), "myresource.txt");
assertTrue(file.canRead());
InputStream fileIs = new FileInputStream(file);
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
-
/**
* TestData provides a convenient interface for managing test output files.
- *
+ *
* @author Erik Brakkee
*/
public final class TestData {
/**
* Obtain root directory of JUnit tests.
- *
+ *
* @return Directory name.
*/
private static File getTestRootDir(Object aTestcase) {
/**
* Returns a temporary directory.
- *
+ *
* @return Temporary directory.
*/
public File getTmpDir() {
/**
* Recursively copy a directory contents to the test output directory.
- *
+ *
* @param sSrc
* Source directory to copy.
*/
/**
* Copies a classpath resource to a relative path in the test output
* directory.
- *
+ *
* @param aResource
* Resource to copy.
* @param aRelativePath
try {
InputStream is = new ClassPathResource(aResource).getInputStream();
FileOutputStream fos = new FileOutputStream(new File(root,
- aRelativePath));
+ aRelativePath));
FileSystemUtils.copyStream(is, fos);
} catch (IOException e) {
e.printStackTrace();
/**
* Copies a resource to the root directory of the test output.
- *
+ *
* @param aResource
* Resource.
*/
/**
* Deletes a file or directory relative to the test output root.
- *
+ *
* @param aRelative
* Relative path. The testcase will fail if the file or directory
* cannot be removed.
/**
* Deletes a directory including its contents.
- *
+ *
* @param aRelative
* Relative path.
*/
/**
* Deletes a directory recursively.
- *
+ *
* @param aRelative
* Relative path.
*/
/**
* Gets the root of the test output directory.
- *
+ *
* @return Root of the test output.
*/
public File getRoot() {
import java.io.File;
-
/**
* Test resource for locating resources in the classpath.
*/
public class TestResource extends FileResource {
/**
* Test class name.
- * @param aTestClass Test class.
- * @param aName Name of the file to look for.
+ *
+ * @param aTestClass
+ * Test class.
+ * @param aName
+ * Name of the file to look for.
*/
public TestResource(Class aTestClass, String aName) {
super(getFile(aTestClass, aName));
/**
* Computes the file path of the file to look for.
- * @param aClass Test class name.
- * @param aName Name of the file.
+ *
+ * @param aClass
+ * Test class name.
+ * @param aName
+ * Name of the file.
* @return File.
*/
private static File getFile(Class aClass, String aName) {
import java.util.ArrayList;
import java.util.List;
-
/**
* Test of the observer pattern implementation.
- *
+ *
* @author Erik Brakkee
*/
public class ObservableTest extends TestCase {
/*
* (non-Javadoc)
- *
+ *
* @see junit.framework.TestCase#setUp()
*/
@Override
super.setUp();
observed = new Integer(1);
observable = new Observable<Integer, String>(observed,
- new DefaultObserverNotifier());
+ new DefaultObserverNotifier());
}
/**
/**
* Subscribes and then unsubscribes with a wrong id. Verifies that
* IllegalArgumentException is thrown.
- *
+ *
*/
public void testUnsubscribeWithWrongSubscription() {
Observer<Integer, String> observer = mock(Observer.class);
import java.util.Map;
import java.util.Set;
-
/**
* Useful assertions for use in test cases.
- *
+ *
* @author Erik Brakkee
*/
public final class AssertionUtils {
/**
* Disabled constructor.
- *
+ *
*/
private AssertionUtils() {
// Empty
/**
* Asserts that two object arrays are equal.
- *
+ *
* @param aExpected
* Expected object array.
* @param aActual
/**
* Asserts that two object arrays are equal.
- *
+ *
* @param aMsg
* Message.
* @param aExpected
}
}
- /**
+/**
* Asserts that two objects are equal, and in case the object is an Object[]
* delegates to {@link #assertEquals(String, Object[], Object[]).
*
/**
* Asserts that two maps are equal by comparing all keys and by checking
* that the values for the same keys are the same.
- *
+ *
* @param aMsg
* Message.
* @param aExpectedMap
*/
public static <Key, Value> void assertEquals(String aMsg,
Map<Key, Value> aExpectedMap, Map<Key, Value> aActual) {
- TestCase.assertEquals("Map sizes differ", aExpectedMap.size(),
- aActual.size());
+ TestCase.assertEquals("Map sizes differ", aExpectedMap.size(), aActual
+ .size());
Set keys = aExpectedMap.keySet();
/**
* Asserts that an exception occurs.
- * @param aRunnable Test cases should create a subclass of this which contains the
- * code that should throw an exception.
- * @param aType Type of exception that is expected.
+ *
+ * @param aRunnable
+ * Test cases should create a subclass of this which contains the
+ * code that should throw an exception.
+ * @param aType
+ * Type of exception that is expected.
*/
public static void assertException(ErroneousCode aObject, Class aType) {
try {
if (aType.isInstance(t)) {
LOG.info("Expected exception occured " + t.getMessage());
- return; // ok
+ return; // ok
} else {
throw new RuntimeException(t);
}
import java.util.List;
import java.util.Map;
-
/**
* Tracks the occurence of certain events in a test environment. Threads in a
* test environment tell the event tracker of the occurrence of certain events
* using {@link #eventOccurred(Event)}. Test code inspects the events sent by a
* thread using {@link #isEventSent(Thread, Event)}.
- *
+ *
* A record is kept of every event which is sent. Therefore, the occurrence of a
* new event does not erase a previously sent event.
- *
+ *
* @param <Event>
* Type of event sent from test code. Usually String will be
* sufficient. The event type must provide a sensible implementation
* of {@link java.lang.Object#equals(java.lang.Object)}.
- *
+ *
* @author Erik Brakkee
*/
public class EventTracker<Event> {
/**
* Constructs the event tracker.
- *
+ *
*/
public EventTracker() {
clear();
/**
* Called by a thread to inform that an event has occurred.
- *
+ *
* @param aEvent
* Event that was sent.
*/
/**
* Checks if a specific event has happened in a specific thread.
- *
+ *
* @param aThread
* Thread to check.
* @param aEvent
/**
* Gets the events for a thread in the order they were sent
- *
+ *
* @param aThread
* Thread to get events for.
* @return Events that were sent. A zero-sized array is returned if no
}
/**
- * Gets the number of times an event was sent summed up
- * over all threads.
- *
+ * Gets the number of times an event was sent summed up over all threads.
+ *
* @param aEvent
* Event to check.
* @return Number of times it was reached.
/**
* Gets the total event count over all threads.
+ *
* @return
*/
public synchronized int getEventCount() {
import junit.framework.TestCase;
-
/**
* Timing utilities.
- *
+ *
* @author Erik Brakkee
*/
public final class TimingUtils {
/**
* Disabled constructor.
- *
+ *
*/
private TimingUtils() {
// Empty
/**
* Sleeps for a time.
- * @param aMillis Number of milliseconds to sleep.
+ *
+ * @param aMillis
+ * Number of milliseconds to sleep.
*/
public static void sleep(int aMillis) {
try {
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
-
/**
* Tests for {@link org.wamblee.xml.ClasspathUriResolver}.
- *
+ *
* @author Erik Brakkee
*/
public class ClasspathUriResolverTest extends TestCase {
private URIResolver resolver;
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see junit.framework.TestCase#setUp()
*/
@Override
/**
* Resolves an existing file. Verifies the file is resolved correctly.
+ *
* @throws TransformerException
* @throws IOException
*/
- public void testResolveExistingFile()
- throws TransformerException, IOException {
- Source source = resolver.resolve("org/wamblee/xml/reportToHtml.xsl", "");
+ public void testResolveExistingFile() throws TransformerException,
+ IOException {
+ Source source = resolver
+ .resolve("org/wamblee/xml/reportToHtml.xsl", "");
assertTrue(source instanceof StreamSource);
- String resolved = FileSystemUtils.read(((StreamSource) source).getInputStream());
+ String resolved = FileSystemUtils.read(((StreamSource) source)
+ .getInputStream());
ClassPathResource resource = new ClassPathResource(
- "org/wamblee/xml/reportToHtml.xsl");
+ "org/wamblee/xml/reportToHtml.xsl");
String expected = FileSystemUtils.read(resource.getInputStream());
assertEquals(expected, resolved);
}
/**
- * Resolves a non-existing file. Verifies that a TransformerException is thrown.
- *
+ * Resolves a non-existing file. Verifies that a TransformerException is
+ * thrown.
+ *
*/
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
}
import java.util.Map;
import java.util.TreeMap;
-
/**
* XML test support utilities.
- *
+ *
* @author Erik Brakkee
*/
public final class XmlUtils {
/**
* Disabled constructor.
- *
+ *
*/
private XmlUtils() {
// Empty
* Checks equality of two XML documents excluding comment and processing
* nodes and trimming the text of the elements. In case of problems, it
* provides an xpath-like expression describing where the problem is.
- *
+ *
* @param aMsg
* @param aExpected
* @param aActual
*/
public static void assertEquals(String aMsg,
org.w3c.dom.Document aExpected, org.w3c.dom.Document aActual) {
- assertEquals(aMsg, DomUtils.convert(aExpected),
- DomUtils.convert(aActual));
+ assertEquals(aMsg, DomUtils.convert(aExpected), DomUtils
+ .convert(aActual));
}
/**
* Checks equality of two XML documents excluding comment and processing
- * nodes and trimming the text of the elements. In case of problems, it
+ * nodes and trimming the text of the elements. In case of problems, it
* provides an xpath-like expression describing where the problem is.
- *
+ *
* @param aMsg
* @param aExpected
* @param aActual
* Checks equality of two XML elements excluding comment and processing
* nodes and trimming the text of the elements. In case of problems, it
* provides an xpath-like expression describing where the problem is.
- *
+ *
* @param aMsg
* @param aExpected
* @param aActual
public static void assertEquals(String aMsg, Element aExpected,
Element aActual) {
// Name.
- TestCase.assertEquals(aMsg + "/name()", aExpected.getName(),
- aActual.getName());
+ TestCase.assertEquals(aMsg + "/name()", aExpected.getName(), aActual
+ .getName());
// Text
TestCase.assertEquals(aMsg + "/text()", aExpected.getTextTrim(),
}
/**
- * Checks equality of two attributes. In case of problems, it
- * provides an xpath-like expression describing where the problem is.
- *
+ * Checks equality of two attributes. In case of problems, it provides an
+ * xpath-like expression describing where the problem is.
+ *
* @param aMsg
* @param aExpected
* @param aActual
*/
public static void assertEquals(String aMsg, Attribute aExpected,
Attribute aActual) {
- TestCase.assertEquals(aMsg + ":name", aExpected.getName(),
- aActual.getName());
- TestCase.assertEquals(aMsg + ":value", aExpected.getValue(),
- aActual.getValue());
+ TestCase.assertEquals(aMsg + ":name", aExpected.getName(), aActual
+ .getName());
+ TestCase.assertEquals(aMsg + ":value", aExpected.getValue(), aActual
+ .getValue());
}
/**
* Comparator which compares attributes by name.
*/
- private static final class AttributeComparator implements Comparator<Attribute> {
+ private static final class AttributeComparator implements
+ Comparator<Attribute> {
/*
* (non-Javadoc)
- *
+ *
* @see java.util.Comparator#compare(T, T)
*/
public int compare(Attribute aAttribute1, Attribute aAttribute2) {
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
-
/**
* Tests the XSL transformer.
- *
+ *
* @author Erik Brakkee
*/
public class XslTransformerTest extends TestCase {
private String getResourcePath(String aResource) {
return getClass().getPackage().getName().replaceAll("\\.", "/") + "/" +
- aResource;
+ aResource;
}
/**
* Transforms a file while using the default resolver, where the included
* file can be found. Verifies the transformation is done correctly.
- *
+ *
*/
public void testTransformUsingDefaultResolver() throws Exception {
XslTransformer transformer = new XslTransformer();
- InputResource xmlResource = new ClassPathResource(getResourcePath(
- REPORT_XML));
+ InputResource xmlResource = new ClassPathResource(
+ getResourcePath(REPORT_XML));
- Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_XSLT)).getInputStream());
+ Source xslt = new StreamSource(new ClassPathResource(
+ getResourcePath(REPORT_TO_HTML_XSLT)).getInputStream());
- byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
- .getBytes();
+ byte[] documentData = FileSystemUtils
+ .read(xmlResource.getInputStream()).getBytes();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
- .newDocumentBuilder();
+ .newDocumentBuilder();
Document document = builder.parse(xmlResource.getInputStream());
Source documentSource = new StreamSource(xmlResource.getInputStream());
- Document expected = DomUtils.read(new ClassPathResource(getResourcePath(
- "output-reportToHtml-report.xml")).getInputStream());
+ Document expected = DomUtils
+ .read(new ClassPathResource(
+ getResourcePath("output-reportToHtml-report.xml"))
+ .getInputStream());
Document output1 = transformer.transform(documentData, xslt);
XmlUtils.assertEquals("byte[] transform", expected, output1);
- xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_XSLT)).getInputStream());
+ xslt = new StreamSource(new ClassPathResource(
+ getResourcePath(REPORT_TO_HTML_XSLT)).getInputStream());
Document output2 = transformer.transform(document, xslt);
XmlUtils.assertEquals("document transform", expected, output2);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Result output = new StreamResult(os);
- xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_XSLT)).getInputStream());
+ xslt = new StreamSource(new ClassPathResource(
+ getResourcePath(REPORT_TO_HTML_XSLT)).getInputStream());
transformer.transform(documentSource, output, xslt);
- XmlUtils.assertEquals("document source transform", expected,
- DomUtils.read(os.toString()));
+ XmlUtils.assertEquals("document source transform", expected, DomUtils
+ .read(os.toString()));
- xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_XSLT)).getInputStream());
+ xslt = new StreamSource(new ClassPathResource(
+ getResourcePath(REPORT_TO_HTML_XSLT)).getInputStream());
String result = transformer.textTransform(documentData, xslt);
- XmlUtils.assertEquals("text transform", expected, DomUtils.read(result));
+ XmlUtils
+ .assertEquals("text transform", expected, DomUtils.read(result));
}
/**
* Transforms a file using the default resolver where the included file
* cannot be found. Verifies that a TransformerException is thrown.
- *
+ *
*/
- public void testTransformUsingDefaultResolverFails()
- throws IOException {
+ public void testTransformUsingDefaultResolverFails() throws IOException {
XslTransformer transformer = new XslTransformer();
- InputResource xmlResource = new ClassPathResource(getResourcePath(
- REPORT_XML));
- Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML2_XSLT)).getInputStream());
+ InputResource xmlResource = new ClassPathResource(
+ getResourcePath(REPORT_XML));
+ Source xslt = new StreamSource(new ClassPathResource(
+ getResourcePath(REPORT_TO_HTML2_XSLT)).getInputStream());
- byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
- .getBytes();
+ byte[] documentData = FileSystemUtils
+ .read(xmlResource.getInputStream()).getBytes();
try {
Document output1 = transformer.transform(documentData, xslt);
/**
* Transforms a file using an invalid Xslt. Verifies that a
* TransformerException is thrown.
- *
+ *
*/
public void testTransformInvalidXslt() throws IOException {
XslTransformer transformer = new XslTransformer();
- InputResource xmlResource = new ClassPathResource(getResourcePath(
- REPORT_XML));
- Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_INVALID_XSLT)).getInputStream());
+ InputResource xmlResource = new ClassPathResource(
+ getResourcePath(REPORT_XML));
+ Source xslt = new StreamSource(new ClassPathResource(
+ getResourcePath(REPORT_TO_HTML_INVALID_XSLT)).getInputStream());
- byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
- .getBytes();
+ byte[] documentData = FileSystemUtils
+ .read(xmlResource.getInputStream()).getBytes();
try {
Document output1 = transformer.transform(documentData, xslt);
/**
* Transforms a file using a non-well formed xslt. Verifies that a
* TransformerException is thrown.
- *
+ *
*/
public void testTransformNonWellformedXslt() throws IOException {
XslTransformer transformer = new XslTransformer();
- InputResource xmlResource = new ClassPathResource(getResourcePath(
- REPORT_XML));
- Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_NONWELLFORMED_XSLT)).getInputStream());
+ InputResource xmlResource = new ClassPathResource(
+ getResourcePath(REPORT_XML));
+ Source xslt = new StreamSource(new ClassPathResource(
+ getResourcePath(REPORT_TO_HTML_NONWELLFORMED_XSLT))
+ .getInputStream());
- byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
- .getBytes();
+ byte[] documentData = FileSystemUtils
+ .read(xmlResource.getInputStream()).getBytes();
try {
Document output1 = transformer.transform(documentData, xslt);
/**
* Transforms a file using a class path resolver.
- *
+ *
*/
public void testTransformUsingClassPathResolver() throws Exception {
- XslTransformer transformer = new XslTransformer(new ClasspathUriResolver());
+ XslTransformer transformer = new XslTransformer(
+ new ClasspathUriResolver());
- InputResource xmlResource = new ClassPathResource(getResourcePath(
- REPORT_XML));
- Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML2_XSLT)).getInputStream());
+ InputResource xmlResource = new ClassPathResource(
+ getResourcePath(REPORT_XML));
+ Source xslt = new StreamSource(new ClassPathResource(
+ getResourcePath(REPORT_TO_HTML2_XSLT)).getInputStream());
- byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
- .getBytes();
+ byte[] documentData = FileSystemUtils
+ .read(xmlResource.getInputStream()).getBytes();
Document output1 = transformer.transform(documentData, xslt);
- Document expected = DomUtils.read(new ClassPathResource(getResourcePath(
- "output-reportToHtml-report.xml")).getInputStream());
+ Document expected = DomUtils
+ .read(new ClassPathResource(
+ getResourcePath("output-reportToHtml-report.xml"))
+ .getInputStream());
XmlUtils.assertEquals("doc", expected, output1);
}
/**
* Transforms a file to text output. Verifies the file is transformed
* correctly.
- *
+ *
*/
public void testTransformToTextOutput() throws Exception {
- XslTransformer transformer = new XslTransformer(new ClasspathUriResolver());
+ XslTransformer transformer = new XslTransformer(
+ new ClasspathUriResolver());
- InputResource xmlResource = new ClassPathResource(getResourcePath(
- REPORT_XML));
- Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_TEXT_XSLT)).getInputStream());
+ InputResource xmlResource = new ClassPathResource(
+ getResourcePath(REPORT_XML));
+ Source xslt = new StreamSource(new ClassPathResource(
+ getResourcePath(REPORT_TO_TEXT_XSLT)).getInputStream());
- byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
- .getBytes();
+ byte[] documentData = FileSystemUtils
+ .read(xmlResource.getInputStream()).getBytes();
String result = transformer.textTransform(documentData, xslt);
String expected = "Hello world!";
}
/**
- * Tests resolving a file using {@link XslTransformer#resolve(String)} with the
- * default resolver where the file does not exist.
- *
+ * Tests resolving a file using {@link XslTransformer#resolve(String)} with
+ * the default resolver where the file does not exist.
+ *
*/
public void testResolveWithDefaultResolverFileNotFound() {
XslTransformer transformer = new XslTransformer();
try {
- Source source = transformer.resolve(
- "org/wamblee/xml/utilities-nonexistent.xsl");
+ Source source = transformer
+ .resolve("org/wamblee/xml/utilities-nonexistent.xsl");
} catch (TransformerException e) {
return; // ok
}
}
/**
- * Tests resolving a file using {@link XslTransformer#resolve(String)} with the
- * default resolver.
- *
+ * Tests resolving a file using {@link XslTransformer#resolve(String)} with
+ * the default resolver.
+ *
*/
public void testResolveWithClasspathResolver() throws Exception {
- XslTransformer transformer = new XslTransformer(new ClasspathUriResolver());
+ XslTransformer transformer = new XslTransformer(
+ new ClasspathUriResolver());
Source source = transformer.resolve(getResourcePath(INCLUDED_XSL_FILE));
assert (source instanceof StreamSource);
StreamSource ssource = (StreamSource) source;
String data = FileSystemUtils.read(ssource.getInputStream());
String expected = FileSystemUtils.read(new ClassPathResource(
- getResourcePath(INCLUDED_XSL_FILE)).getInputStream());
+ getResourcePath(INCLUDED_XSL_FILE)).getInputStream());
assertEquals(expected, data);
}
}
import org.wamblee.concurrency.Lock;
-
/**
- * Locking advice. This automatically synchronized an object using a given
- * lock.
- *
+ * Locking advice. This automatically synchronized an object using a given lock.
+ *
* @author Erik Brakkee
*/
public class LockAdvice implements MethodInterceptor {
*/
private Lock lock;
-/**
- * Constructs lock advice.
- * @param aLock Lock to use.
+ /**
+ * Constructs lock advice.
+ *
+ * @param aLock
+ * Lock to use.
*/
public LockAdvice(Lock aLock) {
lock = aLock;
}
- /* (non-Javadoc)
- * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
- */
- /**
- * DOCUMENT ME!
- *
- * @param aInvocation DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws Throwable DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept
+ * .MethodInvocation)
*/
- public Object invoke(MethodInvocation aInvocation)
- throws Throwable {
+ public Object invoke(MethodInvocation aInvocation) throws Throwable {
lock.acquire();
try {
import org.wamblee.general.BeanFactoryException;
import org.wamblee.general.BeanKernel;
-
/**
* Bean factory which uses Spring. This bean factory cannot be configured
* directly in the {@link org.wamblee.general.BeanKernel} because it does not
* it must tbe subclassed to provide a default constructor.
*/
public class SpringBeanFactory implements BeanFactory {
- /**
- * DOCUMENT ME!
- */
private BeanFactoryReference factoryReference;
-/**
+ /**
* Constructs the bean factory.
*
* @param aSelector
factoryReference = locator.useBeanFactory(aFactoryName);
} catch (BeansException e) {
throw new BeanFactoryException(
- "Could not load bean factory: selector = '" + aSelector
- + "', factory = '" + aFactoryName + "'", e);
+ "Could not load bean factory: selector = '" + aSelector +
+ "', factory = '" + aFactoryName + "'", e);
}
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.general.BeanFactory#find(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aId DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Object find(String aId) {
return find(aId, Object.class);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.general.BeanFactory#find(java.lang.Class)
*/
- /**
- * DOCUMENT ME!
- *
- * @param <T> DOCUMENT ME!
- * @param aClass DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public <T> T find(Class<T> aClass) {
return find(aClass.getName(), aClass);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.general.BeanFactory#find(java.lang.String,
- * java.lang.Class)
- */
- /**
- * DOCUMENT ME!
- *
- * @param <T> DOCUMENT ME!
- * @param aId DOCUMENT ME!
- * @param aClass DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws BeanFactoryException DOCUMENT ME!
+ * java.lang.Class)
*/
public <T> T find(String aId, Class<T> aClass) {
try {
/**
* Gets the spring bean factory.
- *
+ *
* @return Spring bean factory.
*/
public org.springframework.beans.factory.BeanFactory getSpringBeanFactory() {
import java.util.ArrayList;
import java.util.Arrays;
-
/**
* Hibernate mapping files to use.
- *
+ *
* @author Erik Brakkee
*/
public class HibernateMappingFiles extends ArrayList<String> {
-/**
- * Constructs an empty list of hibernate mapping files.
- *
+ /**
+ * Constructs an empty list of hibernate mapping files.
+ *
*/
public HibernateMappingFiles() {
super();
}
-/**
- * Constructs the list of Spring config files.
- * @param aFiles Files.
+ /**
+ * Constructs the list of Spring config files.
+ *
+ * @param aFiles
+ * Files.
*/
public HibernateMappingFiles(String[] aFiles) {
super();
import java.util.Map;
import java.util.Set;
-
/**
- * Extension of {@link
- * org.springframework.orm.hibernate.support.HibernateDaoSupport}.
- *
+ * Extension of
+ * {@link org.springframework.orm.hibernate.support.HibernateDaoSupport}.
+ *
* @author Erik Brakkee
*/
public class HibernateSupport extends HibernateDaoSupport {
- /**
- * DOCUMENT ME!
- */
private static final Log LOG = LogFactory.getLog(HibernateSupport.class);
-/**
+ /**
* Constructs the object.
*
*/
}
/**
- * Performes a hibernate <code>Session.merge()</code> and updates
- * the object with the correct primary key and version. This is an
- * extension to the hibernate merge operation because hibernate itself
- * leaves the object passed to merge untouched. Use this method with
- * extreme caution since it will recursively load all objects that the
- * current object has relations with and for which cascade="merge" was
- * specified in the Hibernate mapping file.
- *
- * @param aPersistent Object to merge.
+ * Performes a hibernate <code>Session.merge()</code> and updates the object
+ * with the correct primary key and version. This is an extension to the
+ * hibernate merge operation because hibernate itself leaves the object
+ * passed to merge untouched. Use this method with extreme caution since it
+ * will recursively load all objects that the current object has relations
+ * with and for which cascade="merge" was specified in the Hibernate mapping
+ * file.
+ *
+ * @param aPersistent
+ * Object to merge.
*/
public void merge(Persistent aPersistent) {
merge(getHibernateTemplate(), aPersistent);
}
/**
- * As {@link #merge(Persistent)} but with a given template. This
- * method can be accessed in a static way.
- *
- * @param aTemplate Hibernate template
- * @param aPersistent Object to merge.
+ * As {@link #merge(Persistent)} but with a given template. This method can
+ * be accessed in a static way.
+ *
+ * @param aTemplate
+ * Hibernate template
+ * @param aPersistent
+ * Object to merge.
*/
public static void merge(HibernateTemplate aTemplate, Persistent aPersistent) {
Persistent merged = (Persistent) aTemplate.merge(aPersistent);
}
/**
- * Copies primary keys and version from the result of the merged to
- * the object that was passed to the merge operation. It does this by
- * traversing the properties of the object. It copies the primary key and
- * version for objects that implement {@link Persistent} and applies the
- * same rules to objects in maps and sets as well (i.e. recursively).
- *
- * @param aPersistent Object whose primary key and version are to be set.
- * @param aMerged Object that was the result of the merge.
- * @param aProcessed List of already processed Persistent objects of the
- * persistent part.
- *
- * @throws RuntimeException DOCUMENT ME!
+ * Copies primary keys and version from the result of the merged to the
+ * object that was passed to the merge operation. It does this by traversing
+ * the properties of the object. It copies the primary key and version for
+ * objects that implement {@link Persistent} and applies the same rules to
+ * objects in maps and sets as well (i.e. recursively).
+ *
+ * @param aPersistent
+ * Object whose primary key and version are to be set.
+ * @param aMerged
+ * Object that was the result of the merge.
+ * @param aProcessed
+ * List of already processed Persistent objects of the persistent
+ * part.
+ *
*/
public static void processPersistent(Persistent aPersistent,
Persistent aMerged, List<ObjectElem> aProcessed) {
}
if ((aPersistent == null) || (aMerged == null)) {
- throw new RuntimeException("persistent or merged object is null '"
- + aPersistent + "'" + " '" + aMerged + "'");
+ throw new RuntimeException("persistent or merged object is null '" +
+ aPersistent + "'" + " '" + aMerged + "'");
}
ObjectElem elem = new ObjectElem(aPersistent);
LOG.debug("Setting pk/version on " + aPersistent + " from " + aMerged);
- if ((aPersistent.getPrimaryKey() != null)
- && !aMerged.getPrimaryKey().equals(aPersistent.getPrimaryKey())) {
- LOG.error("Mismatch between primary key values: " + aPersistent
- + " " + aMerged);
+ if ((aPersistent.getPrimaryKey() != null) &&
+ !aMerged.getPrimaryKey().equals(aPersistent.getPrimaryKey())) {
+ LOG.error("Mismatch between primary key values: " + aPersistent +
+ " " + aMerged);
} else {
aPersistent.setPersistedVersion(aMerged.getPersistedVersion());
aPersistent.setPrimaryKey(aMerged.getPrimaryKey());
try {
if (Set.class.isAssignableFrom(returnType)) {
- Set merged = (Set) getter.invoke(aMerged);
+ Set merged = (Set) getter.invoke(aMerged);
Set persistent = (Set) getter.invoke(aPersistent);
processSet(persistent, merged, aProcessed);
} else if (List.class.isAssignableFrom(returnType)) {
- List merged = (List) getter.invoke(aMerged);
+ List merged = (List) getter.invoke(aMerged);
List persistent = (List) getter.invoke(aPersistent);
processList(persistent, merged, aProcessed);
} else if (Map.class.isAssignableFrom(returnType)) {
- Map merged = (Map) getter.invoke(aMerged);
+ Map merged = (Map) getter.invoke(aMerged);
Map persistent = (Map) getter.invoke(aPersistent);
processMap(persistent, merged, aProcessed);
} else if (Persistent.class.isAssignableFrom(returnType)) {
- Persistent merged = (Persistent) getter.invoke(aMerged);
- Persistent persistent = (Persistent) getter.invoke(aPersistent);
+ Persistent merged = (Persistent) getter.invoke(aMerged);
+ Persistent persistent = (Persistent) getter
+ .invoke(aPersistent);
processPersistent(persistent, merged, aProcessed);
- } else if (returnType.isArray()
- && Persistent.class.isAssignableFrom(
- returnType.getComponentType())) {
- Persistent[] merged = (Persistent[]) getter.invoke(aMerged);
- Persistent[] persistent = (Persistent[]) getter.invoke(aPersistent);
+ } else if (returnType.isArray() &&
+ Persistent.class.isAssignableFrom(returnType
+ .getComponentType())) {
+ Persistent[] merged = (Persistent[]) getter
+ .invoke(aMerged);
+ Persistent[] persistent = (Persistent[]) getter
+ .invoke(aPersistent);
for (int i = 0; i < persistent.length; i++) {
processPersistent(persistent[i], merged[i],
/**
* Process the persistent objects in the collections.
- *
- * @param aPersistent Collection in the original object.
- * @param aMerged Collection as a result of the merge.
- * @param aProcessed List of processed persistent objects.
- *
- * @throws RuntimeException DOCUMENT ME!
+ *
+ * @param aPersistent
+ * Collection in the original object.
+ * @param aMerged
+ * Collection as a result of the merge.
+ * @param aProcessed
+ * List of processed persistent objects.
+ *
*/
public static void processList(List aPersistent, List aMerged,
List<ObjectElem> aProcessed) {
- Object[] merged = aMerged.toArray();
+ Object[] merged = aMerged.toArray();
Object[] persistent = aPersistent.toArray();
if (merged.length != persistent.length) {
- throw new RuntimeException("Array sizes differ " + merged.length
- + " " + persistent.length);
+ throw new RuntimeException("Array sizes differ " + merged.length +
+ " " + persistent.length);
}
for (int i = 0; i < merged.length; i++) {
/**
* Process the persistent objects in sets.
- *
- * @param aPersistent Collection in the original object.
- * @param aMerged Collection as a result of the merge.
- * @param aProcessed List of processed persistent objects.
- *
- * @throws RuntimeException DOCUMENT ME!
+ *
+ * @param aPersistent
+ * Collection in the original object.
+ * @param aMerged
+ * Collection as a result of the merge.
+ * @param aProcessed
+ * List of processed persistent objects.
+ *
*/
public static void processSet(Set aPersistent, Set aMerged,
List<ObjectElem> aProcessed) {
if (aMerged.size() != aPersistent.size()) {
- throw new RuntimeException("Array sizes differ " + aMerged.size()
- + " " + aPersistent.size());
+ throw new RuntimeException("Array sizes differ " + aMerged.size() +
+ " " + aPersistent.size());
}
for (Object merged : aMerged) {
/**
* Process the Map objects in the collections.
- *
- * @param aPersistent Collection in the original object.
- * @param aMerged Collection as a result of the merge.
- * @param aProcessed List of processed persistent objects.
- *
- * @throws RuntimeException DOCUMENT ME!
+ *
+ * @param aPersistent
+ * Collection in the original object.
+ * @param aMerged
+ * Collection as a result of the merge.
+ * @param aProcessed
+ * List of processed persistent objects.
+ *
*/
public static void processMap(Map aPersistent, Map aMerged,
List<ObjectElem> aProcessed) {
if (aMerged.size() != aPersistent.size()) {
- throw new RuntimeException("Sizes differ " + aMerged.size() + " "
- + aPersistent.size());
+ throw new RuntimeException("Sizes differ " + aMerged.size() + " " +
+ aPersistent.size());
}
Set keys = aMerged.keySet();
throw new RuntimeException("Key '" + key + "' not found");
}
- Object mergedValue = aMerged.get(key);
+ Object mergedValue = aMerged.get(key);
Object persistentValue = aPersistent.get(key);
if (mergedValue instanceof Persistent) {
}
/**
- * This class provided an equality operation based on the object
- * reference of the wrapped object. This is required because we cannto
- * assume that the equals operation has any meaning for different types of
- * persistent objects. This allows us to use the standard collection
- * classes for detecting cyclic dependences and avoiding recursion.
+ * This class provided an equality operation based on the object reference
+ * of the wrapped object. This is required because we cannto assume that the
+ * equals operation has any meaning for different types of persistent
+ * objects. This allows us to use the standard collection classes for
+ * detecting cyclic dependences and avoiding recursion.
*/
private static final class ObjectElem {
private Object object;
import org.wamblee.test.TimingUtils;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author Erik Brakkee
*/
public class LockAdviceTest extends AbstractLockTestCase {
- /**
- * DOCUMENT ME!
- */
private Runnable target;
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.concurrency.AbstractLockTestCase#setUp()
*/
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
super.setUp();
- Runner runner = new Runner();
- LockAdvice advice = new LockAdvice(new JvmLock());
+ Runner runner = new Runner();
+ LockAdvice advice = new LockAdvice(new JvmLock());
ProxyFactoryBean support = new ProxyFactoryBean();
support.setInterfaces(new Class[] { Runnable.class });
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.concurrency.AbstractLockTestCase#runThread()
*/
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws RuntimeException DOCUMENT ME!
- */
@Override
protected Thread runThread() {
Thread t = new Thread(new Runnable() {
- public void run() {
- try {
- getTracker().eventOccurred(STARTED);
- target.run();
- getTracker().eventOccurred(RELEASED);
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
- ;
- });
+ public void run() {
+ try {
+ getTracker().eventOccurred(STARTED);
+ target.run();
+ getTracker().eventOccurred(RELEASED);
+ } catch (Throwable e) {
+ throw new RuntimeException(e);
+ }
+ };
+ });
t.start();
return t;
import org.wamblee.general.BeanFactoryException;
-
/**
* Tests the spring bean factory.
- *
+ *
* @author Erik Brakkee
*/
public class SpringBeanFactoryTest extends TestCase {
/*
* (non-Javadoc)
- *
+ *
* @see junit.framework.TestCase#setUp()
*/
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
super.setUp();
}
- /**
- * DOCUMENT ME!
- */
public void testExistingBeanRefContext() {
- SpringBeanFactory factory = new SpringBeanFactory("org/wamblee/general/beanRefContext.xml",
- "test");
+ SpringBeanFactory factory = new SpringBeanFactory(
+ "org/wamblee/general/beanRefContext.xml", "test");
- String value1 = factory.find(String.class);
+ String value1 = factory.find(String.class);
assertEquals("hello", value1);
String value2 = (String) factory.find("java.lang.String");
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testUnknownBeanFactory() {
try {
new SpringBeanFactory("org/wamblee/general/beanRefContext.xml",
/**
* Test bean factory.
- *
+ *
* @author Erik Brakkee
*/
public class TestBeanFactory extends SpringBeanFactory {
-/**
+ /**
* Creates a new TestBeanFactory object.
*/
public TestBeanFactory() {
import java.io.File;
import java.io.IOException;
-
/**
* Exporting the hibernate mapping.
- *
+ *
* @author Erik Brakkee
*/
public final class HibernateExporter {
-/**
+ /**
* Disabled constructor.
- *
+ *
*/
private HibernateExporter() {
// Empty
}
- /**
- * DOCUMENT ME!
- *
- * @param aArgs DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
public static void main(String[] aArgs) throws IOException {
- String file = aArgs[0];
- File dir = new File(aArgs[1]);
+ String file = aArgs[0];
+ File dir = new File(aArgs[1]);
- Configuration conf = HibernateUtils.getConfiguration(dir);
+ Configuration conf = HibernateUtils.getConfiguration(dir);
- SchemaExport export = new SchemaExport(conf);
+ SchemaExport export = new SchemaExport(conf);
export.setDelimiter(";");
export.setOutputFile(file);
export.create(true, false);
import java.io.File;
import java.io.IOException;
-
/**
* Exporting the hibernate mapping.
- *
+ *
* @author Erik Brakkee
*/
public final class HibernateUpdater {
-/**
+ /**
* Disabled constructor.
- *
+ *
*/
private HibernateUpdater() {
// Empty
}
- /**
- * DOCUMENT ME!
- *
- * @param aArgs DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
public static void main(String[] aArgs) throws IOException {
- String file = aArgs[0];
- File dir = new File(file);
+ String file = aArgs[0];
+ File dir = new File(file);
- Configuration conf = HibernateUtils.getConfiguration(dir);
+ Configuration conf = HibernateUtils.getConfiguration(dir);
- SchemaUpdate lSchemaUpdate = new SchemaUpdate(conf);
+ SchemaUpdate lSchemaUpdate = new SchemaUpdate(conf);
lSchemaUpdate.execute(true, true);
}
}
import java.util.Properties;
import java.util.TreeMap;
-
/**
* Hibernate utilities.
- *
+ *
* @author Erik Brakkee
*/
public final class HibernateUtils {
- /**
- * DOCUMENT ME!
- */
private static final String DATABASE_PROPS = "test.database.properties";
-/**
+ /**
* Disabled.
- *
+ *
*/
private HibernateUtils() {
// Empty
}
/**
- * DOCUMENT ME!
- *
+ *
* @param aDir
- *
+ *
* @return
- *
- * @throws IOException DOCUMENT ME!
+ *
*/
- public static Configuration getConfiguration(File aDir)
- throws IOException {
- Configuration conf = new Configuration();
- File[] files = aDir.listFiles((FileFilter) (new AwkFilenameFilter(
- ".*\\.hbm\\.xml")));
+ public static Configuration getConfiguration(File aDir) throws IOException {
+ Configuration conf = new Configuration();
+ File[] files = aDir.listFiles((FileFilter) (new AwkFilenameFilter(
+ ".*\\.hbm\\.xml")));
for (File f : files) {
System.out.println("Mapping file: " + f);
Map<String, String> dbProps = getHibernateProperties();
for (Map.Entry<String, String> entry : dbProps.entrySet()) {
- System.out.println("Property: " + entry.getKey() + "="
- + entry.getValue());
+ System.out.println("Property: " + entry.getKey() + "=" +
+ entry.getValue());
conf.setProperty(entry.getKey(), entry.getValue());
}
return conf;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
private static Map<String, String> getHibernateProperties()
throws IOException {
System.out.println("Reading properties file: " + DATABASE_PROPS);
InputResource lPropFile = new ClassPathResource(DATABASE_PROPS);
- Properties props = new Properties();
+ Properties props = new Properties();
props.load(lPropFile.getInputStream());
Map<String, String> result = new TreeMap<String, String>();
- result.put("hibernate.connection.driver_class",
- props.getProperty("database.driver"));
- result.put("hibernate.connection.url", props.getProperty("database.url"));
- result.put("hibernate.connection.username",
- props.getProperty("database.username"));
- result.put("hibernate.connection.password",
- props.getProperty("database.password"));
+ result.put("hibernate.connection.driver_class", props
+ .getProperty("database.driver"));
+ result.put("hibernate.connection.url", props
+ .getProperty("database.url"));
+ result.put("hibernate.connection.username", props
+ .getProperty("database.username"));
+ result.put("hibernate.connection.password", props
+ .getProperty("database.password"));
return result;
}
import org.wamblee.general.BeanFactory;
import org.wamblee.general.BeanFactoryException;
-
/**
* Bean factory which uses Spring.
- *
+ *
* @author Erik Brakkee
*/
public class TestSpringBeanFactory implements BeanFactory {
- /**
- * DOCUMENT ME!
- */
private ApplicationContext context;
-/**
+ /**
* Creates a new TestSpringBeanFactory object.
- *
- * @param aContext DOCUMENT ME!
+ *
*/
public TestSpringBeanFactory(ApplicationContext aContext) {
context = aContext;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.general.BeanFactory#find(java.lang.String)
*/
- /**
- * DOCUMENT ME!
- *
- * @param aId DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Object find(String aId) {
return find(aId, Object.class);
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.wamblee.general.BeanFactory#find(java.lang.Class)
*/
- /**
- * DOCUMENT ME!
- *
- * @param <T> DOCUMENT ME!
- * @param aClass DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public <T> T find(Class<T> aClass) {
return find(aClass.getName(), aClass);
}
- /* (non-Javadoc)
- * @see org.wamblee.general.BeanFactory#find(java.lang.String, java.lang.Class)
- */
- /**
- * DOCUMENT ME!
- *
- * @param <T> DOCUMENT ME!
- * @param aId DOCUMENT ME!
- * @param aClass DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws BeanFactoryException DOCUMENT ME!
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.wamblee.general.BeanFactory#find(java.lang.String,
+ * java.lang.Class)
*/
public <T> T find(String aId, Class<T> aClass) {
try {
import java.util.Map;
-
/**
* Transaction callback for testing. The test will fail if any type of exception
* is thrown.
- *
+ *
* @author Erik Brakkee
*/
public interface TestTransactionCallback {
/**
- * Executes code within a transaction, causing the testcase to fail
- * if any type of exception is thrown.
- *
+ * Executes code within a transaction, causing the testcase to fail if any
+ * type of exception is thrown.
+ *
* @return A map containg the resuls of the execution. This is a convenient
* method of returning multiple results from a call.
- *
- * @throws Exception DOCUMENT ME!
+ *
*/
Map execute() throws Exception;
}
/**
* Transaction callback for testing. The test will fail if any type of exception
* is thrown.
- *
+ *
* @author Erik Brakkee
*/
public interface TestTransactionCallbackWithoutResult {
/**
- * Executes code within a transaction, causing the testcase to fail
- * if any type of exception is thrown.
- *
- * @throws Exception DOCUMENT ME!
+ * Executes code within a transaction, causing the testcase to fail if any
+ * type of exception is thrown.
+ *
*/
void execute() throws Exception;
}
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
-
/**
* A Class Adapter adapts a given class to a Component.
- *
+ *
* @author Erik Brakkee
*/
public class ClassAdapter extends AbstractComponent<Object> {
- /**
- * DOCUMENT ME!
- */
private ClassConfiguration _classConfig;
/**
* Creates a new ClassAdapter object.
- *
- * @param aName DOCUMENT ME!
- * @param aClassConfig DOCUMENT ME!
+ *
*/
public ClassAdapter(String aName, ClassConfiguration aClassConfig) {
- super(aName,
- aClassConfig.getProvidedInterfaces()
- .toArray(new ProvidedInterface[0]),
- aClassConfig.getRequiredInterfaces()
+ super(aName, aClassConfig.getProvidedInterfaces().toArray(
+ new ProvidedInterface[0]), aClassConfig.getRequiredInterfaces()
.toArray(new RequiredInterface[0]));
_classConfig = aClassConfig;
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Object doStart(Scope aScope) {
Object obj = _classConfig.create(aScope);
return obj;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
protected void doStop(Object aRuntime) {
- // Empty.
+ // Empty.
}
}
import java.util.ArrayList;
import java.util.List;
-
/**
- * The class configuration encapsulates the knowledge of how to wrap a
- * class as a component.
- *
+ * The class configuration encapsulates the knowledge of how to wrap a class as
+ * a component.
+ *
* @author Erik Brakkee
*/
public class ClassConfiguration {
- /**
- * DOCUMENT ME!
- */
private Class _class;
- /**
- * DOCUMENT ME!
- */
private ConstructorConfiguration constructorConfig;
- /**
- * DOCUMENT ME!
- */
private ObjectConfiguration objectConfig;
-/**
- * Constructs the configuration. By default no constructor is selected and
- * one of {@link #select(Class...)} or
- * {@link #greedy()} must be called.
- * @param aClass Class to construct.
- */
+ /**
+ * Constructs the configuration. By default no constructor is selected and
+ * one of {@link #select(Class...)} or {@link #greedy()} must be called.
+ *
+ * @param aClass
+ * Class to construct.
+ */
public ClassConfiguration(Class aClass) {
- _class = aClass;
- constructorConfig = new ConstructorConfiguration(aClass);
- objectConfig = new ObjectConfiguration(aClass);
+ _class = aClass;
+ constructorConfig = new ConstructorConfiguration(aClass);
+ objectConfig = new ObjectConfiguration(aClass);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public ConstructorConfiguration getConstructorConfig() {
return constructorConfig;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public ObjectConfiguration getObjectConfig() {
return objectConfig;
}
/**
* Creates the object in the given scope.
- *
- * @param aScope Scope containing required interfaces for this object.
- *
+ *
+ * @param aScope
+ * Scope containing required interfaces for this object.
+ *
* @return object.
*/
public Object create(Scope aScope) {
/**
* Injects required interfaces through the setters
- *
- * @param aScope Scope in which injection takes place.
- * @param aObject Object to inject into.
+ *
+ * @param aScope
+ * Scope in which injection takes place.
+ * @param aObject
+ * Object to inject into.
*/
public void inject(Scope aScope, Object aObject) {
objectConfig.inject(aScope, aObject);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public List<ProvidedInterface> getProvidedInterfaces() {
List<ProvidedInterface> result = new ArrayList<ProvidedInterface>();
result.add(new DefaultProvidedInterface("provided", _class));
return result;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public List<RequiredInterface> getRequiredInterfaces() {
List<RequiredInterface> result = new ArrayList<RequiredInterface>();
result.addAll(constructorConfig.getRequiredInterfaces());
import java.util.Arrays;
import java.util.List;
-
/**
- * Class that allows configuration of the constructor to use. In
- * particular, it provides:
- * <ul>
- * <li>Selection of a constructor using explicit selection {@link
- * #select(Class...)} or using the most greedy constructor {@link
- * #greedy()}.</li>
- * <li>Selection of methods to invoke to inject other objects into
- * the object.</li>
- * <li>Selection of fields to set.</li>
- * </ul>
+ * Class that allows configuration of the constructor to use. In particular, it
+ * provides:
+ * <ul>
+ * <li>Selection of a constructor using explicit selection
+ * {@link #select(Class...)} or using the most greedy constructor
+ * {@link #greedy()}.</li>
+ * <li>Selection of methods to invoke to inject other objects into the object.</li>
+ * <li>Selection of fields to set.</li>
+ * </ul>
*/
public class ConstructorConfiguration {
- /**
- * DOCUMENT ME!
- */
private Class clazz;
- /**
- * DOCUMENT ME!
- */
private Constructor<?> constructor;
- /**
- * DOCUMENT ME!
- */
private ParameterValues values;
- /**
- * DOCUMENT ME!
- */
private boolean publicOnly;
-/**
- * Constructs the configuration. By default the public constructor with the
- * most arguments will be used.
- * @param aClass Class to construct.
- */
+ /**
+ * Constructs the configuration. By default the public constructor with the
+ * most arguments will be used.
+ *
+ * @param aClass
+ * Class to construct.
+ */
public ConstructorConfiguration(Class aClass) {
- clazz = aClass;
- constructor = null;
- publicOnly = true;
+ clazz = aClass;
+ constructor = null;
+ publicOnly = true;
}
/**
- * Sets whether or no non public constructors are also considered.
- * Reset the choice of a constructor to its default.
- *
+ * Sets whether or no non public constructors are also considered. Reset the
+ * choice of a constructor to its default.
+ *
* @param aNonPublic
- *
+ *
* @return
*/
public ConstructorConfiguration setNonPublic(boolean aNonPublic) {
- publicOnly = !aNonPublic;
- constructor = null;
- values = null;
+ publicOnly = !aNonPublic;
+ constructor = null;
+ values = null;
return this;
}
/**
* Selects an explicit constructor.
- *
+ *
* @return Return the injector to allow call chaining.
- *
- * @throws SystemAssemblyException DOCUMENT ME!
+ *
*/
public ConstructorConfiguration select(Class... aTypes) {
try {
/**
* Selects the greediest constructor.
- *
+ *
* @return The injector to allow call chaining.
- *
- * @throws SystemAssemblyException if the greediest constructor cannot be
- * uniquely identified.
+ *
+ * @throws SystemAssemblyException
+ * if the greediest constructor cannot be uniquely identified.
*/
public ConstructorConfiguration greedy() {
Constructor<?>[] declared = clazz.getDeclaredConstructors();
if (declared.length == 0) {
- throw new SystemAssemblyException("Class '" + clazz
- + " is an interface, primitive type, or array");
+ throw new SystemAssemblyException("Class '" + clazz +
+ " is an interface, primitive type, or array");
}
- int max = -1;
+ int max = -1;
List<Constructor<?>> checked = new ArrayList<Constructor<?>>();
CollectionFilter.filter(Arrays.asList(declared), checked,
new Condition<Constructor<?>>() {
}
}
- final int max2 = max;
- List<Constructor<?>> ctors = checked;
+ final int max2 = max;
+ List<Constructor<?>> ctors = checked;
List<Constructor<?>> longest = new ArrayList<Constructor<?>>();
CollectionFilter.filter(ctors, longest,
new Condition<Constructor<?>>() {
/**
* Creates the object in the given scope.
- *
- * @param aScope Scope containing required interfaces for this object.
- *
+ *
+ * @param aScope
+ * Scope containing required interfaces for this object.
+ *
* @return object.
- *
- * @throws SystemAssemblyException DOCUMENT ME!
+ *
*/
public Object create(Scope aScope) {
Object[] valueArray = values.values(aScope);
try {
return getConstructor().newInstance(valueArray);
} catch (Exception e) {
- throw new SystemAssemblyException("Could not construct object "
- + getConstructor() + " " + Arrays.asList(valueArray), e);
+ throw new SystemAssemblyException("Could not construct object " +
+ getConstructor() + " " + Arrays.asList(valueArray), e);
}
}
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class DefaultContainer extends Container {
/**
* Creates a new DefaultContainer object.
- *
- * @param aName DOCUMENT ME!
+ *
*/
public DefaultContainer(String aName) {
super(aName);
}
- /**
- * DOCUMENT ME!
- *
- * @param aComponent DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public DefaultContainer addComponent(Component aComponent) {
super.addComponent(aComponent);
return this;
}
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- * @param aConfiguration DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public DefaultContainer addComponent(String aName,
ClassConfiguration aConfiguration) {
return addComponent(new ClassAdapter(aName, aConfiguration));
}
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- * @param aObject DOCUMENT ME!
- * @param aConfiguration DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public DefaultContainer addComponent(String aName, Object aObject,
ObjectConfiguration aConfiguration) {
if (!aConfiguration.appliesTo(aObject)) {
- throw new IllegalArgumentException("Configuration '"
- + aConfiguration + "' does nto applu to '" + aObject + "'");
+ throw new IllegalArgumentException("Configuration '" +
+ aConfiguration + "' does nto applu to '" + aObject + "'");
}
return addComponent(new ObjectAdapter(aName, aObject, aConfiguration));
}
- /**
- * DOCUMENT ME!
- *
- * @param aRequired DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public DefaultContainer addRequiredInterface(RequiredInterface aRequired) {
super.addRequiredInterface(aRequired);
return this;
}
- /**
- * DOCUMENT ME!
- *
- * @param aProvided DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public DefaultContainer addProvidedInterface(ProvidedInterface aProvided) {
super.addProvidedInterface(aProvided);
import org.wamblee.system.core.Scope;
-
/**
* Value provider that provides a fixed value.
- *
+ *
* @author Erik Brakkee
*/
class FixedValueProvider implements ValueProvider {
- /**
- * DOCUMENT ME!
- */
private Object _value;
-/**
- * Constructs the value.
- * @param aValue Value to construct.
- */
+ /**
+ * Constructs the value.
+ *
+ * @param aValue
+ * Value to construct.
+ */
public FixedValueProvider(Object aValue) {
_value = aValue;
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Object getValue(Scope aScope) {
return _value;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
-
/**
* An adapter class that adapts an existing object to a component.
- *
+ *
* @author Erik Brakkee
*/
public class ObjectAdapter extends AbstractComponent<Object> {
- /**
- * DOCUMENT ME!
- */
private ObjectConfiguration objectConfig;
- /**
- * DOCUMENT ME!
- */
private Object object;
/**
* Creates a new ObjectAdapter object.
- *
- * @param aName DOCUMENT ME!
- * @param aObject DOCUMENT ME!
- * @param aObjectConfig DOCUMENT ME!
+ *
*/
public ObjectAdapter(String aName, Object aObject,
ObjectConfiguration aObjectConfig) {
- super(aName,
- new ProvidedInterface[] {
- new DefaultProvidedInterface(aName, aObject.getClass())
- },
- aObjectConfig.getRequiredInterfaces()
+ super(aName, new ProvidedInterface[] { new DefaultProvidedInterface(
+ aName, aObject.getClass()) }, aObjectConfig.getRequiredInterfaces()
.toArray(new RequiredInterface[0]));
- objectConfig = aObjectConfig;
- object = aObject;
+ objectConfig = aObjectConfig;
+ object = aObject;
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Object doStart(Scope aScope) {
objectConfig.inject(aScope, object);
return object;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
protected void doStop(Object aRuntime) {
- // Empty.
+ // Empty.
}
}
import java.util.ArrayList;
import java.util.List;
-
/**
* General configuration for an instantiated object.
- *
+ *
* @author Erik Brakkee
*/
public class ObjectConfiguration {
- /**
- * DOCUMENT ME!
- */
private Class _class;
- /**
- * DOCUMENT ME!
- */
private SetterConfiguration setterConfig;
/**
* Creates a new ObjectConfiguration object.
- *
- * @param aClass DOCUMENT ME!
+ *
*/
public ObjectConfiguration(Class aClass) {
- _class = aClass;
- setterConfig = new SetterConfiguration(aClass);
+ _class = aClass;
+ setterConfig = new SetterConfiguration(aClass);
}
/**
* Performs injection into an object of the configured class using
* information from the given scope.
- *
- * @param aScope Scope.
- * @param aObject Object.
+ *
+ * @param aScope
+ * Scope.
+ * @param aObject
+ * Object.
*/
public void inject(Scope aScope, Object aObject) {
setterConfig.inject(aScope, aObject);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public SetterConfiguration getSetterConfig() {
return setterConfig;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public List<RequiredInterface> getRequiredInterfaces() {
List<RequiredInterface> result = new ArrayList<RequiredInterface>();
result.addAll(setterConfig.getRequiredInterfaces());
return result;
}
- /**
- * DOCUMENT ME!
- *
- * @param aObject DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean appliesTo(Object aObject) {
return _class.isInstance(aObject);
}
import java.util.ArrayList;
import java.util.List;
-
/**
- * Represents parameter values for a method or constructor and allows for
- * the configuration of how these values are retrieved.
- *
+ * Represents parameter values for a method or constructor and allows for the
+ * configuration of how these values are retrieved.
+ *
* @author Erik Brakkee
*/
public class ParameterValues {
- /**
- * DOCUMENT ME!
- */
private String[] names;
- /**
- * DOCUMENT ME!
- */
private Class[] types;
- /**
- * DOCUMENT ME!
- */
private ValueProvider[] values;
-/**
- * Constructs the configuration. By default no constructor is selected and
- * one of {@link #select(Class...)} or
- * {@link #greedy()} must be called.
- * @param aClass Class to construct.
- */
+ /**
+ * Constructs the configuration. By default no constructor is selected and
+ * one of {@link #select(Class...)} or {@link #greedy()} must be called.
+ *
+ * @param aClass
+ * Class to construct.
+ */
public ParameterValues(Class[] aTypes) {
names = new String[aTypes.length];
resetValues();
}
-/**
- * Constructs the configuration. By default no constructor is selected and
- * one of {@link #select(Class...)} or
- * {@link #greedy()} must be called.
- * @param aNames Names of the arguments.
- * @param aClass Class to construct.
+ /**
+ * Constructs the configuration. By default no constructor is selected and
+ * one of {@link #select(Class...)} or {@link #greedy()} must be called.
+ *
+ * @param aNames
+ * Names of the arguments.
+ * @param aClass
+ * Class to construct.
*/
public ParameterValues(String[] aNames, Class[] aTypes) {
assert aNames.length == aTypes.length;
- names = aNames;
- types = aTypes;
+ names = aNames;
+ types = aTypes;
resetValues();
}
/**
* The types of the parameter values.
- *
+ *
* @return Types.
*/
public Class[] getTypes() {
}
/**
- * Sets argument i to be optional, meaning that null is allowed to
- * be passed in.
- *
- * @param aArg Argument to set.
- *
- * @return DOCUMENT ME!
+ * Sets argument i to be optional, meaning that null is allowed to be passed
+ * in.
+ *
+ * @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;
}
/**
* Sets the argument i to a fixed value.
- *
- * @param aArg Argument to set.
- * @param aValue Value.
- *
- * @return DOCUMENT ME!
+ *
+ * @param aArg
+ * Argument to set.
+ * @param aValue
+ * Value.
+ *
*/
public ParameterValues setValue(int aArg, Object aValue) {
values[aArg] = new FixedValueProvider(aValue);
values = new ValueProvider[types.length];
for (int i = 0; i < values.length; i++) {
- values[i] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
- names[i], types[i]));
+ values[i] = new RequiredInterfaceProvider(
+ new DefaultRequiredInterface(names[i], types[i]));
}
}
/**
- * Gets the required interfaces to provide values that are not
- * provided in another way.
- *
+ * Gets the required interfaces to provide values that are not provided in
+ * another way.
+ *
* @return Required interfaces.
*/
public List<RequiredInterface> getRequiredInterfaces() {
/**
* Returns the values to use in the given scope.
- *
- * @param aScope Scope within which to retrieve the values.
- *
+ *
+ * @param aScope
+ * Scope within which to retrieve the values.
+ *
* @return Values.
*/
public Object[] values(Scope aScope) {
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
-
/**
* Value provider that provides a value through a required interface.
- *
+ *
* @author Erik Brakkee
*/
class RequiredInterfaceProvider implements ValueProvider {
- /**
- * DOCUMENT ME!
- */
private RequiredInterface required;
-/**
- * Constructs the provider
- * @param aRequired Required interface.
- */
+ /**
+ * Constructs the provider
+ *
+ * @param aRequired
+ * Required interface.
+ */
public RequiredInterfaceProvider(RequiredInterface aRequired) {
required = aRequired;
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Object getValue(Scope aScope) {
return aScope.getInterfaceImplementation(required.getProvider(),
Object.class);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public RequiredInterface getRequiredInterface() {
return required;
}
import java.util.Map;
import java.util.Set;
-
/**
- * Represents the configuration for exposing the setters of a class as
- * required interfaces.
- *
+ * Represents the configuration for exposing the setters of a class as required
+ * interfaces.
+ *
* @author Erik Brakkee
*/
public class SetterConfiguration {
- /**
- * DOCUMENT ME!
- */
private Class _class;
- /**
- * DOCUMENT ME!
- */
private boolean publicOnly;
- /**
- * DOCUMENT ME!
- */
private Map<Method, ParameterValues> setters;
-/**
- * Constructs the setter configuration. By default no setters are added.
- *
- * @param aClass
- * Class which is being configured.
- */
+ /**
+ * Constructs the setter configuration. By default no setters are added.
+ *
+ * @param aClass
+ * Class which is being configured.
+ */
public SetterConfiguration(Class aClass) {
- _class = aClass;
- publicOnly = true;
- setters = new HashMap<Method, ParameterValues>();
+ _class = aClass;
+ publicOnly = true;
+ setters = new HashMap<Method, ParameterValues>();
}
/**
* Makes sure that all available setters are used.
- *
- * @return DOCUMENT ME!
+ *
*/
public SetterConfiguration initAllSetters() {
setters.clear();
}
/**
- * Called to set whether non-public setters are also used. By
- * default only public setters are used. The currently selected setters
- * remain chosen.
- *
- * @param aIsNonPublic Non public flag.
- *
- * @return DOCUMENT ME!
+ * Called to set whether non-public setters are also used. By default only
+ * public setters are used. The currently selected setters remain chosen.
+ *
+ * @param aIsNonPublic
+ * Non public flag.
+ *
*/
public SetterConfiguration setNonPublic(boolean aIsNonPublic) {
publicOnly = !aIsNonPublic;
/**
* Removes all setters.
- *
+ *
* @return Reference to the current object to allow call chaining.
*/
public SetterConfiguration clear() {
/**
* Removes a setter from the set of methods.
- *
- * @param aName Name of the setter to remove.
- *
+ *
+ * @param aName
+ * Name of the setter to remove.
+ *
* @return Reference to the current object to allow call chaining.
- *
- * @throws IllegalArgumentException DOCUMENT ME!
+ *
*/
public SetterConfiguration remove(String aName) {
for (Method method : setters.keySet()) {
/**
* Removes the method from the set of methods.
- *
- * @param aMethod Method to remove.
- *
+ *
+ * @param aMethod
+ * Method to remove.
+ *
* @return
- *
- * @throws RuntimeException DOCUMENT ME!
- * @throws IllegalArgumentException DOCUMENT ME!
+ *
*/
public SetterConfiguration remove(Method aMethod) {
if (!aMethod.getDeclaringClass().isAssignableFrom(_class)) {
- throw new RuntimeException("Method " + aMethod
- + " not found in class " + _class + " or its superclasses");
+ throw new RuntimeException("Method " + aMethod +
+ " not found in class " + _class + " or its superclasses");
}
for (Method method : setters.keySet()) {
}
}
- throw new IllegalArgumentException("Method '" + aMethod
- + "' was not configured. ");
+ throw new IllegalArgumentException("Method '" + aMethod +
+ "' was not configured. ");
}
/**
* Adds a given setter name to the setters.
- *
- * @param aName Name of a setter method.
- *
+ *
+ * @param aName
+ * Name of a setter method.
+ *
* @return Reference to the current object to allow call chaining.
- *
- * @throws IllegalArgumentException DOCUMENT ME!
+ *
*/
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,
new Condition<Method>() {
});
if (methods.size() == 0) {
- throw new IllegalArgumentException("Method '" + aName
- + "' not found in " + _class.getName());
+ throw new IllegalArgumentException("Method '" + aName +
+ "' not found in " + _class.getName());
}
- // TODO is it possible to get more than one setter here in case the subclass overrides
- // the baseclass method?
+ // 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)));
return this;
}
/**
- * Adds a given setter identified by the type it accepts to the
- * list of setters.N
- *
- * @param aType Type to look for. Note that this must be the exact type as
- * autoboxing and autounboxing is not used.
- *
+ * Adds a given setter identified by the type it accepts to the list of
+ * setters.N
+ *
+ * @param aType
+ * Type to look for. Note that this must be the exact type as
+ * autoboxing and autounboxing is not used.
+ *
* @return Reference to the current object to allow call chaining.
- *
- * @throws IllegalArgumentException In case no setter is found or multiple
- * setters are found.
+ *
+ * @throws IllegalArgumentException
+ * In case no setter is found or multiple setters are found.
*/
public SetterConfiguration addSetter(final Class aType) {
List<Method> result = new ArrayList<Method>();
});
if (result.size() == 0) {
- throw new IllegalArgumentException("No setter found in class '"
- + _class.getName() + "' that has a setter with argument type '"
- + aType.getName() + "'");
+ throw new IllegalArgumentException("No setter found in class '" +
+ _class.getName() + "' that has a setter with argument type '" +
+ aType.getName() + "'");
}
if (result.size() > 1) {
}
throw new IllegalArgumentException(
- "Multiple setters found in class '" + _class.getName()
- + " that accept type '" + aType.getName() + "': " + setters);
+ "Multiple setters found in class '" + _class.getName() +
+ " that accept type '" + aType.getName() + "': " + setters);
}
Method method = result.get(0);
/**
* Gets all setters for the current class.
- *
- * @param aClass DOCUMENT ME!
- * @param aPublicOnly DOCUMENT ME!
- *
+ *
+ *
* @return List of all setters.
*/
public static List<Method> getAllSetters(Class aClass, boolean aPublicOnly) {
for (Method method : getAllMethods(aClass)) {
if (!aPublicOnly || Modifier.isPublic(method.getModifiers())) {
- if (method.getName().startsWith("set")
- && (method.getParameterTypes().length == 1)) {
+ if (method.getName().startsWith("set") &&
+ (method.getParameterTypes().length == 1)) {
method.setAccessible(true);
result.add(method);
}
return result;
}
- /**
- * DOCUMENT ME!
- *
- * @param aMethod DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static ParameterValues createParameterValues(Method aMethod) {
- Class[] paramTypes = aMethod.getParameterTypes();
+ Class[] paramTypes = aMethod.getParameterTypes();
String[] paramNames = new String[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
return new ParameterValues(paramNames, paramTypes);
}
- /**
- * DOCUMENT ME!
- *
- * @param aClass DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static final List<Method> getAllMethods(Class aClass) {
return ReflectionUtils.getAllMethods(aClass);
}
/**
* Gets the required interfaces based on the configured setteres.
- *
+ *
* @return List of required interfaces.
*/
public List<RequiredInterface> getRequiredInterfaces() {
/**
* Invokes all configured setters with the appropriate values.
- *
- * @param aScope Scope within which invocation takes place.
- * @param aObject Object on which the invocation takes place.
- *
- * @throws IllegalArgumentException DOCUMENT ME!
- * @throws SystemAssemblyException DOCUMENT ME!
+ *
+ * @param aScope
+ * Scope within which invocation takes place.
+ * @param aObject
+ * Object on which the invocation takes place.
+ *
*/
public void inject(Scope aScope, Object aObject) {
if (!_class.isInstance(aObject)) {
- throw new IllegalArgumentException("Object '" + aObject
- + "' is not an instance of " + _class.getName());
+ throw new IllegalArgumentException("Object '" + aObject +
+ "' is not an instance of " + _class.getName());
}
for (Method method : setters.keySet()) {
try {
method.invoke(aObject, values.values(aScope));
} catch (IllegalAccessException e) {
- throw new SystemAssemblyException("Problem invoking " + method
- + " with " + values, e);
+ throw new SystemAssemblyException("Problem invoking " + method +
+ " with " + values, e);
} catch (InvocationTargetException e) {
- throw new SystemAssemblyException("Problem invoking " + method
- + " with " + values, e);
+ throw new SystemAssemblyException("Problem invoking " + method +
+ " with " + values, e);
}
}
}
/**
- * Returns the parameter values for allowing detailed configuration
- * of how parameter values are set.
- *
- * @param aMethod Setter name without the "set" prefix with the first
- * character converted to lower case.
- *
+ * Returns the parameter values for allowing detailed configuration of how
+ * parameter values are set.
+ *
+ * @param aMethod
+ * Setter name without the "set" prefix with the first character
+ * converted to lower case.
+ *
* @return Parameter values.
- *
- * @throws IllegalArgumentException DOCUMENT ME!
+ *
*/
public ParameterValues values(String aMethod) {
for (Method method : setters.keySet()) {
}
}
- throw new IllegalArgumentException("No setter method '" + aMethod
- + "' found");
+ throw new IllegalArgumentException("No setter method '" + aMethod +
+ "' found");
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public List<Method> getSetters() {
return new ArrayList<Method>(setters.keySet());
}
import org.wamblee.system.core.Scope;
-
/**
- * Interface used to provide values for arguments of methods and constructors.
+ * Interface used to provide values for arguments of methods and constructors.
*
* @author Erik Brakkee
*/
interface ValueProvider {
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
Object getValue(Scope aScope);
}
import java.util.Properties;
-
/**
* Property component that reads a property file and provides it to other
- * components through a provided interface. NOTE: when multiple property
+ * components through a provided interface. NOTE: when multiple property
* components are used, disambiguation of provided and required interfaces is
* needed.
- *
+ *
* @author Erik Brakkee
*/
public class PropertyComponent extends AbstractComponent<Properties> {
- /**
- * DOCUMENT ME!
- */
- private static ProvidedInterface PROPS = new DefaultProvidedInterface("props",
- Properties.class);
+ private static ProvidedInterface PROPS = new DefaultProvidedInterface(
+ "props", Properties.class);
- /**
- * DOCUMENT ME!
- */
private Properties props;
/**
* Creates a new PropertyComponent object.
- *
- * @param aName DOCUMENT ME!
- * @param aResource DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
+ *
+ *
*/
public PropertyComponent(String aName, InputResource aResource)
throws IOException {
/**
* Creates a new PropertyComponent object.
- *
- * @param aName DOCUMENT ME!
- * @param aProps DOCUMENT ME!
+ *
*/
public PropertyComponent(String aName, Properties aProps) {
super(aName);
addProvidedInterface(PROPS);
}
- /**
- * DOCUMENT ME!
- *
- * @param aResource DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
private static Properties readProps(InputResource aResource)
throws IOException {
Properties props = new Properties();
return props;
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Properties doStart(Scope aScope) {
addInterface(PROPS, props, aScope);
return props;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
protected void doStop(Properties aRuntime) {
- // Empty
+ // Empty
}
}
import java.util.Arrays;
import java.util.List;
-
/**
* Container consisting of multiple components.
- *
+ *
* @author Erik Brakkee
*/
public class Container extends AbstractComponent<Scope> {
- /**
- * DOCUMENT ME!
- */
private static final Log LOG = LogFactory.getLog(Container.class);
- /**
- * DOCUMENT ME!
- */
private List<Component> components;
- /**
- * DOCUMENT ME!
- */
private CompositeEdgeFilter edgeFilter;
- /**
- * DOCUMENT ME!
- */
private boolean sealed;
-/**
+ /**
* Constructs the container
*
* @param aName
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);
}
}
-/**
+ /**
* Constructs the container
*
* @param aName
*/
public Container(String aName, Component[] aComponents,
ProvidedInterface[] aProvided, RequiredInterface[] aRequired) {
- this(aName, aComponents, Arrays.asList(aProvided),
- Arrays.asList(aRequired));
+ this(aName, aComponents, Arrays.asList(aProvided), Arrays
+ .asList(aRequired));
}
/**
* Creates a new Container object.
- *
- * @param aName DOCUMENT ME!
+ *
*/
public Container(String aName) {
this(aName, new Component[0], new ProvidedInterface[0],
new RequiredInterface[0]);
}
- /**
- * DOCUMENT ME!
- *
- * @param aComponent DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Container addComponent(Component aComponent) {
checkSealed();
if (aComponent.getContext() != null) {
throw new SystemAssemblyException(
- "Inconsistent hierarchy, component '" + aComponent.getName()
- + "' is already part of another hierarchy");
+ "Inconsistent hierarchy, component '" + aComponent.getName() +
+ "' is already part of another hierarchy");
}
if (findComponent(aComponent.getName()) != null) {
- throw new SystemAssemblyException("Duplicate component '"
- + aComponent.getName() + "'");
+ throw new SystemAssemblyException("Duplicate component '" +
+ aComponent.getName() + "'");
}
components.add(aComponent);
/**
* Explictly connects required and provided interfaces.
- *
- * @param aClientComponent Client component, may not be null.
- * @param aRequiredInterface Required interface. If null it means all
- * required interfaces.
- * @param aServerComponent Server component to connect to. If null, it
- * means that no server components may be connected to and the
- * provider of the required interface will be null.
- * @param aProvidedInterface Provided interface. If null, it means that
- * there is no restriction on the name of the provided interface
- * and that it is automatically selected.
- *
- * @throws SystemAssemblyException DOCUMENT ME!
+ *
+ * @param aClientComponent
+ * Client component, may not be null.
+ * @param aRequiredInterface
+ * Required interface. If null it means all required interfaces.
+ * @param aServerComponent
+ * Server component to connect to. If null, it means that no
+ * server components may be connected to and the provider of the
+ * required interface will be null.
+ * @param aProvidedInterface
+ * Provided interface. If null, it means that there is no
+ * restriction on the name of the provided interface and that it
+ * is automatically selected.
+ *
*/
public void connectRequiredProvided(String aClientComponent,
String aRequiredInterface, String aServerComponent,
Component server = findComponent(aServerComponent);
if (client == null) {
- throw new SystemAssemblyException(getQualifiedName()
- + ": No component '" + aClientComponent + "' in the container");
+ throw new SystemAssemblyException(getQualifiedName() +
+ ": No component '" + aClientComponent + "' in the container");
}
if (aRequiredInterface != null) {
- if (findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null) {
- throw new SystemAssemblyException(getQualifiedName()
- + ": Component '" + aClientComponent
- + "' does not have a required interface named '"
- + aRequiredInterface + "'");
+ if (findInterface(client.getRequiredInterfaces(),
+ aRequiredInterface) == null) {
+ throw new SystemAssemblyException(getQualifiedName() +
+ ": Component '" + aClientComponent +
+ "' does not have a required interface named '" +
+ aRequiredInterface + "'");
}
}
if (server == null) {
- throw new SystemAssemblyException("No component '"
- + aClientComponent + "' in the container");
+ throw new SystemAssemblyException("No component '" +
+ aClientComponent + "' in the container");
}
if (aProvidedInterface != null) {
- if (findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) {
- throw new SystemAssemblyException(getQualifiedName()
- + ": Component '" + aServerComponent
- + "' does not have a provided interface named '"
- + aProvidedInterface + "'");
+ if (findInterface(server.getProvidedInterfaces(),
+ aProvidedInterface) == null) {
+ throw new SystemAssemblyException(getQualifiedName() +
+ ": Component '" + aServerComponent +
+ "' does not have a provided interface named '" +
+ aProvidedInterface + "'");
}
}
edgeFilter.add(new ConnectRequiredProvidedEdgeFilter(aClientComponent,
- aRequiredInterface, aServerComponent, aProvidedInterface));
+ aRequiredInterface, aServerComponent, aProvidedInterface));
}
/**
- * Explicitly connects a externally required interface to an
- * internally required interface.
- *
- * @param aComponent Component requiring the interface (must be non-null).
- * @param aRequiredInterface Required interface of the component (must be
- * non-null).
- * @param aExternalRequiredInterface Externally required interface (must be
- * non-null).
- *
- * @throws SystemAssemblyException DOCUMENT ME!
+ * Explicitly connects a externally required interface to an internally
+ * required interface.
+ *
+ * @param aComponent
+ * Component requiring the interface (must be non-null).
+ * @param aRequiredInterface
+ * Required interface of the component (must be non-null).
+ * @param aExternalRequiredInterface
+ * Externally required interface (must be non-null).
+ *
*/
public void connectExternalRequired(String aComponent,
String aRequiredInterface, String aExternalRequiredInterface) {
Component client = findComponent(aComponent);
if (client == null) {
- throw new SystemAssemblyException(getQualifiedName()
- + ": No component '" + aComponent + "' in the container");
+ throw new SystemAssemblyException(getQualifiedName() +
+ ": No component '" + aComponent + "' in the container");
}
if (aRequiredInterface != null) {
- if (findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null) {
- throw new SystemAssemblyException(getQualifiedName()
- + ": Component '" + aComponent
- + "' does not have a required interface named '"
- + aRequiredInterface + "'");
+ if (findInterface(client.getRequiredInterfaces(),
+ aRequiredInterface) == null) {
+ throw new SystemAssemblyException(getQualifiedName() +
+ ": Component '" + aComponent +
+ "' does not have a required interface named '" +
+ aRequiredInterface + "'");
}
}
if (aExternalRequiredInterface != null) {
if (findInterface(getRequiredInterfaces(),
- aExternalRequiredInterface) == null) {
- throw new SystemAssemblyException(getQualifiedName()
- + ": container does not have a required interface named '"
- + aExternalRequiredInterface + "'");
+ aExternalRequiredInterface) == null) {
+ throw new SystemAssemblyException(getQualifiedName() +
+ ": container does not have a required interface named '" +
+ aExternalRequiredInterface + "'");
}
}
edgeFilter.add(new ConnectRequiredExternallyRequiredEdgeFilter(
- aComponent, aRequiredInterface, aExternalRequiredInterface));
+ aComponent, aRequiredInterface, aExternalRequiredInterface));
}
- /**
- * DOCUMENT ME!
- *
- * @param aExternalProvided DOCUMENT ME!
- * @param aComponent DOCUMENT ME!
- * @param aProvidedInterface DOCUMENT ME!
- */
public void connectExternalProvided(String aExternalProvided,
String aComponent, String aProvidedInterface) {
checkSealed();
Component server = findComponent(aComponent);
if (server == null) {
- throw new SystemAssemblyException("No component '" + aComponent
- + "' in the container");
+ throw new SystemAssemblyException("No component '" + aComponent +
+ "' in the container");
}
if (aProvidedInterface != null) {
- if (findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) {
- throw new SystemAssemblyException(getQualifiedName()
- + ": Component '" + aComponent
- + "' does not have a provided interface named '"
- + aProvidedInterface + "'");
+ if (findInterface(server.getProvidedInterfaces(),
+ aProvidedInterface) == null) {
+ throw new SystemAssemblyException(getQualifiedName() +
+ ": Component '" + aComponent +
+ "' does not have a provided interface named '" +
+ aProvidedInterface + "'");
}
}
if (aExternalProvided != null) {
if (findInterface(getProvidedInterfaces(), aExternalProvided) == null) {
- throw new SystemAssemblyException(getQualifiedName()
- + ": Container does not have a provided interface named '"
- + aExternalProvided + "'");
+ throw new SystemAssemblyException(getQualifiedName() +
+ ": Container does not have a provided interface named '" +
+ aExternalProvided + "'");
}
}
edgeFilter.add(new ConnectExternalProvidedProvidedFilter(
- aExternalProvided, aComponent, aProvidedInterface));
+ aExternalProvided, aComponent, aProvidedInterface));
}
- /**
- * DOCUMENT ME!
- *
- * @param aProvided DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Container addProvidedInterface(ProvidedInterface aProvided) {
checkSealed();
return this;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRequired DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Container addRequiredInterface(RequiredInterface aRequired) {
checkSealed();
return this;
}
- /**
- * DOCUMENT ME!
- *
- * @param aContext DOCUMENT ME!
- */
@Override
public void addContext(String aContext) {
super.addContext(aContext);
}
/**
- * Validates the components together to check that there are no
- * required services not in the required list and no services in the
- * provided list that cannot be provided. Also logs a warning in case of
- * superfluous requirements.
+ * Validates the components together to check that there are no required
+ * services not in the required list and no services in the provided list
+ * that cannot be provided. Also logs a warning in case of superfluous
+ * requirements.
*/
public void validate() {
doStartOptionalDryRun(null, true);
}
/**
- * Seal the container, meaning that no further components or
- * interfaces may be added.
+ * Seal the container, meaning that no further components or interfaces may
+ * be added.
*/
public void seal() {
sealed = true;
/**
* Checks if the container is sealed.
- *
+ *
* @return True iff the container is sealed.
*/
public boolean isSealed() {
}
/**
- * Utility method to start with an empty external scope. This is
- * useful for top-level containers which are not part of another
- * container.
- *
+ * Utility method to start with an empty external scope. This is useful for
+ * top-level containers which are not part of another container.
+ *
* @return Scope.
*/
public Scope start() {
return super.start(scope);
}
- /**
- * DOCUMENT ME!
- *
- * @param aExternalScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Scope doStart(Scope aExternalScope) {
validate();
- Scope scope = new DefaultScope(getProvidedInterfaces()
- .toArray(new ProvidedInterface[0]), aExternalScope);
+ Scope scope = new DefaultScope(getProvidedInterfaces().toArray(
+ new ProvidedInterface[0]), aExternalScope);
ComponentGraph graph = doStartOptionalDryRun(scope, false);
exposeProvidedInterfaces(graph, aExternalScope, scope);
seal();
return scope;
}
- /**
- * DOCUMENT ME!
- *
- * @param aGraph DOCUMENT ME!
- * @param aExternalScope DOCUMENT ME!
- * @param aInternalScope DOCUMENT ME!
- */
private void exposeProvidedInterfaces(ComponentGraph aGraph,
Scope aExternalScope, Scope aInternalScope) {
for (Pair<ProvidedInterface, ProvidedInterface> mapping : aGraph
.findExternalProvidedInterfaceMapping()) {
Object svc = aInternalScope.getInterfaceImplementation(mapping
- .getSecond(), Object.class);
+ .getSecond(), Object.class);
addInterface(mapping.getFirst(), svc, aExternalScope);
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- * @param aDryRun DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private ComponentGraph doStartOptionalDryRun(Scope aScope, boolean aDryRun) {
ComponentGraph graph = createComponentGraph();
graph.validate();
} catch (SystemAssemblyException e) {
throw e;
} catch (RuntimeException e) {
- LOG.error(getQualifiedName() + ": could not start '"
- + component.getQualifiedName() + "'", e);
+ LOG.error(getQualifiedName() + ": could not start '" +
+ component.getQualifiedName() + "'", e);
stopAlreadyStartedComponents(started, aScope);
throw e;
}
return graph;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private ComponentGraph createComponentGraph() {
ComponentGraph graph = new ComponentGraph();
return graph;
}
- /**
- * DOCUMENT ME!
- *
- * @param aStarted DOCUMENT ME!
- * @param aScope DOCUMENT ME!
- */
private void stopAlreadyStartedComponents(List<Component> aStarted,
Scope aScope) {
// an exception occurred, stop the successfully started
Component component = aStarted.get(i);
aStarted.get(i).stop(aScope.getRuntime(component));
} catch (Throwable t) {
- LOG.error(getQualifiedName() + ": error stopping "
- + aStarted.get(i).getQualifiedName());
+ LOG.error(getQualifiedName() + ": error stopping " +
+ aStarted.get(i).getQualifiedName());
}
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- */
@Override
protected void doStop(Scope aScope) {
for (int i = components.size() - 1; i >= 0; i--) {
Component component = components.get(i);
- Object runtime = aScope.getRuntime(component);
+ Object runtime = aScope.getRuntime(component);
component.stop(runtime);
}
}
- /**
- * DOCUMENT ME!
- */
private void checkSealed() {
if (sealed) {
throw new SystemAssemblyException("Container is sealed");
}
/**
- * Finds a component based on the non-qualified name of the
- * component.
- *
- * @param aName Component name.
- *
+ * Finds a component based on the non-qualified name of the component.
+ *
+ * @param aName
+ * Component name.
+ *
* @return Component or null if not found.
*/
public Component findComponent(String aName) {
return null;
}
- /**
- * DOCUMENT ME!
- *
- * @param <T> DOCUMENT ME!
- * @param aInterfaces DOCUMENT ME!
- * @param aInterfaceName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static <T extends NamedInterface> T findInterface(
List<T> aInterfaces, String aInterfaceName) {
for (T intf : aInterfaces) {
import java.util.Collections;
import java.util.List;
-
/**
* Abstract subsystem class making it easy to implement new subsystems.
- *
- * @param <Type> DOCUMENT ME!
+ *
*/
public abstract class AbstractComponent<Type> implements Component<Type> {
- /**
- * DOCUMENT ME!
- */
private static final Log LOG = LogFactory.getLog(AbstractComponent.class);
- /**
- * DOCUMENT ME!
- */
private ThreadLocal<List<ProvidedInterface>> remaining;
- /**
- * DOCUMENT ME!
- */
private String context;
- /**
- * DOCUMENT ME!
- */
private String name;
- /**
- * DOCUMENT ME!
- */
private List<ProvidedInterface> provided;
- /**
- * DOCUMENT ME!
- */
private List<RequiredInterface> required;
-/**
- * Constructs the subsystem.
- *
- * @param aName
- * Name of the system.
- * @param aProvided
- * Provided services.
- * @param aRequired
- * Required services.
- */
+ /**
+ * Constructs the subsystem.
+ *
+ * @param aName
+ * Name of the system.
+ * @param aProvided
+ * Provided services.
+ * @param aRequired
+ * Required services.
+ */
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);
}
-/**
+ /**
* Constructs the subsystem.
*
* @param aName
/**
* Creates a new AbstractComponent object.
- *
- * @param aName DOCUMENT ME!
+ *
*/
protected AbstractComponent(String aName) {
this(aName, new ProvidedInterface[0], new RequiredInterface[0]);
}
- /**
- * DOCUMENT ME!
- *
- * @param aProvided DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public AbstractComponent<Type> addProvidedInterface(
ProvidedInterface aProvided) {
provided.add(aProvided);
return this;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRequired DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public AbstractComponent<Type> addRequiredInterface(
RequiredInterface aRequired) {
required.add(aRequired);
return this;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public final String getName() {
return name;
}
- /**
- * DOCUMENT ME!
- *
- * @param aContext DOCUMENT ME!
- */
@Override
public void addContext(String aContext) {
if (context == null) {
}
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getContext() {
return context;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getQualifiedName() {
if (context == null) {
return context + "." + getName();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public final List<ProvidedInterface> getProvidedInterfaces() {
return Collections.unmodifiableList(provided);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public final List<RequiredInterface> getRequiredInterfaces() {
return Collections.unmodifiableList(required);
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public final Type start(Scope aScope) {
LOG.info("Initialization starting '" + getQualifiedName() + "'");
List<ProvidedInterface> oldRemaining = remaining.get();
- remaining.set(new ArrayList<ProvidedInterface>(getProvidedInterfaces()));
+ remaining
+ .set(new ArrayList<ProvidedInterface>(getProvidedInterfaces()));
try {
Type runtime = doStart(aScope);
}
}
- /**
- * DOCUMENT ME!
- */
private void checkNotStartedInterfaces() {
if (remaining.get().size() > 0) {
String notProvided = "";
for (ProvidedInterface provided : remaining.get()) {
- notProvided += ("\nComponent " + getQualifiedName()
- + " did not start interface " + provided);
+ notProvided += ("\nComponent " + getQualifiedName() +
+ " did not start interface " + provided);
}
throw new SystemAssemblyException(notProvided);
}
/**
- * Must be implemented for initializing the subsystem. The
- * implementation must call {@link #addInterface(ProvidedInterface,
- * Object, Scope)} for each service that is started.
- *
- * @param aScope DOCUMENT ME!
- *
+ * Must be implemented for initializing the subsystem. The implementation
+ * must call {@link #addInterface(ProvidedInterface, Object, Scope)} for
+ * each service that is started.
+ *
+ *
* @return Returns the runtime of the component.
*/
protected abstract Type doStart(Scope aScope);
/**
- * Implementations must call this method to indicate that a new
- * service has been started.
- *
- * @param aDescriptor Provided interface.
- * @param aService Implementation of the interface.
- * @param aScope scope in which to publish the implementation.
- *
- * @throws SystemAssemblyException DOCUMENT ME!
+ * Implementations must call this method to indicate that a new service has
+ * been started.
+ *
+ * @param aDescriptor
+ * Provided interface.
+ * @param aService
+ * Implementation of the interface.
+ * @param aScope
+ * scope in which to publish the implementation.
+ *
*/
protected final void addInterface(ProvidedInterface aDescriptor,
Object aService, Scope aScope) {
- LOG.info("Interface '" + getQualifiedName() + "."
- + aDescriptor.getName() + "' started.");
+ LOG.info("Interface '" + getQualifiedName() + "." +
+ aDescriptor.getName() + "' started.");
if (!remaining.get().remove(aDescriptor)) {
- throw new SystemAssemblyException("Component '"
- + getQualifiedName() + "' started an unexpected interface '"
- + aDescriptor
- + "' that was not registerd as a provided interface before");
+ throw new SystemAssemblyException("Component '" +
+ getQualifiedName() + "' started an unexpected interface '" +
+ aDescriptor +
+ "' that was not registerd as a provided interface before");
}
aScope.publishInterface(aDescriptor, aService);
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
public void stop(Type aRuntime) {
LOG.info("Stopping initiated '" + getQualifiedName() + "'");
LOG.info("Stopping completed '" + getQualifiedName() + "'");
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
protected abstract void doStop(Type aRuntime);
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return getQualifiedName();
}
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public ProvidedInterface findProvidedInterface(String aName) {
for (ProvidedInterface provided : getProvidedInterfaces()) {
if (provided.getName().equals(aName)) {
return null;
}
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public RequiredInterface findRequiredInterface(String aName) {
for (RequiredInterface required : getRequiredInterfaces()) {
if (required.getName().equals(aName)) {
import java.util.List;
-
/**
- * A component represents a part of a system that requires a
- * number of interfaces and provides a number of interfaces.
+ * A component represents a part of a system that requires a number of
+ * interfaces and provides a number of interfaces.
+ *
+ * The component interface provides the meta-data for a component. After calling
+ * {@link #start(Scope)}, an actual runtime representation of the component can
+ * be created which is independent of this component. As a special case, the
+ * runtime representation may be identical to the component instance but in
+ * general it is not. This allows a component to be used as a factory for
+ * creating objects.
*
- * The component interface provides the meta-data for a component.
- * After calling {@link #start(Scope)}, an actual runtime representation of the
- * component can be created which is independent of this component.
- * As a special case, the runtime representation may be identical to the
- * component instance but in general it is not. This allows a component to be
- * used as a factory for creating objects.
*
- *
* @author Erik Brakkee
*/
public interface Component<Type> {
/**
* Gets the name of the subsystem.
- *
+ *
* @return Subsystem name.
*/
String getName();
/**
* Prepends the context with a super context.
- *
- * @param aContext DOCUMENT ME!
+ *
*/
void addContext(String aContext);
/**
* Getst the context.
- *
+ *
* @return Context or null if not set.
*/
String getContext();
/**
- * Gets the fully qualified name of the component which includes
- * the context of the component. This method can only be used after the
- * component has started.
- *
+ * Gets the fully qualified name of the component which includes the context
+ * of the component. This method can only be used after the component has
+ * started.
+ *
* @return Qualified name.
*/
String getQualifiedName();
/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ * Gets a description of the provided interfaces.
+ *
+ * @return Provided interfaces.
*/
-/**
- * Gets a description of the provided interfaces.
- * @return Provided interfaces.
- */
List<ProvidedInterface> getProvidedInterfaces();
/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ * Gets a description of the required interfaces.
+ *
+ * @return Required interfaces.
*/
-/**
- * Gets a description of the required interfaces.
- * @return Required interfaces.
- */
List<RequiredInterface> getRequiredInterfaces();
/**
- * Initialises the subsystem by starting all the services that it
- * described as provided.
- *
- * @param aScope Scope with external interface implementations that are
- * available. The component must publish its runtime and its
- * provided interfaces in this scope.
- *
+ * Initialises the subsystem by starting all the services that it described
+ * as provided.
+ *
+ * @param aScope
+ * Scope with external interface implementations that are
+ * available. The component must publish its runtime and its
+ * provided interfaces in this scope.
+ *
* @return Gets an object representing the runtime of the component.
*/
Type start(Scope aScope);
/**
* Stops a component.
- *
- * @param aRuntime THe runtime part of the component.
+ *
+ * @param aRuntime
+ * THe runtime part of the component.
*/
void stop(Type aRuntime);
}
import java.util.Collections;
import java.util.List;
-
/**
* Default implementation of a service descriptor.
- *
+ *
* @author Erik Brakkee
*/
public class DefaultProvidedInterface implements ProvidedInterface {
- /**
- * DOCUMENT ME!
- */
private String name;
- /**
- * DOCUMENT ME!
- */
private Class[] interfaces;
-/**
- * Constructs the descriptor.
- * @param aInterface Type of service.
- */
+ /**
+ * Constructs the descriptor.
+ *
+ * @param aInterface
+ * Type of service.
+ */
public DefaultProvidedInterface(String aName, Class aInterface) {
this(aName, new Class[] { aInterface });
}
-/**
+ /**
* Creates a new DefaultProvidedInterface object.
- *
- * @param aName DOCUMENT ME!
- * @param aInterfaces DOCUMENT ME!
+ *
*/
public DefaultProvidedInterface(String aName, Class[] aInterfaces) {
- name = aName;
- interfaces = Arrays.copyOf(aInterfaces, aInterfaces.length);
+ name = aName;
+ interfaces = Arrays.copyOf(aInterfaces, aInterfaces.length);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getName() {
return name;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Class[] getInterfaceTypes() {
return interfaces;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
return buf.toString();
}
- /**
- * DOCUMENT ME!
- *
- * @param aObj DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean equals(Object aObj) {
return this == aObj;
/*
- if ( !(aObj instanceof DefaultProvidedInterface)) {
- return false;
- }
- DefaultProvidedInterface provided = (DefaultProvidedInterface)aObj;
- return getEqualsRepresentation().equals(provided.getEqualsRepresentation());
- */
+ * if ( !(aObj instanceof DefaultProvidedInterface)) { return false; }
+ * DefaultProvidedInterface provided = (DefaultProvidedInterface)aObj;
+ * return
+ * getEqualsRepresentation().equals(provided.getEqualsRepresentation());
+ */
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public int hashCode() {
return getEqualsRepresentation().hashCode();
}
- /**
- * DOCUMENT ME!
- *
- * @param aInterface DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean covers(ProvidedInterface aInterface) {
- // TODO do more than just equals.
+ // TODO do more than just equals.
if (!(aInterface instanceof DefaultProvidedInterface)) {
return false;
}
- return getEqualsRepresentation()
- .equals(((DefaultProvidedInterface) aInterface).getEqualsRepresentation());
+ return getEqualsRepresentation().equals(
+ ((DefaultProvidedInterface) aInterface).getEqualsRepresentation());
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private String getEqualsRepresentation() {
List<String> result = new ArrayList<String>();
import java.util.Arrays;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class DefaultRequiredInterface implements RequiredInterface {
- /**
- * DOCUMENT ME!
- */
private String name;
- /**
- * DOCUMENT ME!
- */
private boolean optional;
- /**
- * DOCUMENT ME!
- */
private Class[] required;
- /**
- * DOCUMENT ME!
- */
private ProvidedInterface provider;
-/**
+ /**
* Creates a new DefaultRequiredInterface object.
- *
- * @param aName DOCUMENT ME!
- * @param aInterface DOCUMENT ME!
+ *
*/
public DefaultRequiredInterface(String aName, Class aInterface) {
this(aName, new Class[] { aInterface });
}
-/**
+ /**
* Creates a new DefaultRequiredInterface object.
- *
- * @param aName DOCUMENT ME!
- * @param aInterfaces DOCUMENT ME!
+ *
*/
public DefaultRequiredInterface(String aName, Class[] aInterfaces) {
this(aName, aInterfaces, false);
}
-/**
+ /**
* Creates a new DefaultRequiredInterface object.
- *
- * @param aName DOCUMENT ME!
- * @param aInterface DOCUMENT ME!
- * @param aIsOptional DOCUMENT ME!
+ *
*/
public DefaultRequiredInterface(String aName, Class aInterface,
boolean aIsOptional) {
this(aName, new Class[] { aInterface }, aIsOptional);
}
-/**
+ /**
* Creates a new DefaultRequiredInterface object.
- *
- * @param aName DOCUMENT ME!
- * @param aInterfaces DOCUMENT ME!
- * @param aIsOptional DOCUMENT ME!
+ *
*/
public DefaultRequiredInterface(String aName, Class[] aInterfaces,
boolean aIsOptional) {
- name = aName;
- optional = aIsOptional;
- required = aInterfaces;
+ name = aName;
+ optional = aIsOptional;
+ required = aInterfaces;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getName() {
return name;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean isOptional() {
return optional;
}
- /**
- * DOCUMENT ME!
- *
- * @param aDescriptor DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean implementedBy(ProvidedInterface aDescriptor) {
Class[] provided = aDescriptor.getInterfaceTypes();
}
/**
- * Check if the required interface is implemented by one of the
- * provided interfaces.
- *
- * @param aRequired required interface
- * @param aProvided Provided interfaces.
- *
+ * Check if the required interface is implemented by one of the provided
+ * interfaces.
+ *
+ * @param aRequired
+ * required interface
+ * @param aProvided
+ * Provided interfaces.
+ *
* @return
*/
private boolean serviceProvided(Class aRequired, Class[] aProvided) {
for (Class provided : aProvided) {
try {
- provided = ReflectionUtils.wrapIfNeeded(provided);
- aRequired = ReflectionUtils.wrapIfNeeded(aRequired);
+ provided = ReflectionUtils.wrapIfNeeded(provided);
+ aRequired = ReflectionUtils.wrapIfNeeded(aRequired);
provided.asSubclass(aRequired);
return true;
return false;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public ProvidedInterface getProvider() {
return provider;
}
- /**
- * DOCUMENT ME!
- *
- * @param aProvider DOCUMENT ME!
- */
@Override
public void setProvider(ProvidedInterface aProvider) {
assert aProvider != null;
provider = aProvider;
}
- /**
- * DOCUMENT ME!
- *
- * @param obj DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean equals(Object obj) {
return this == obj;
}
- /**
- * DOCUMENT ME!
- *
- * @param obj DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean covers(RequiredInterface obj) {
- // TODO do more than equals.
+ // TODO do more than equals.
if (!(obj instanceof DefaultRequiredInterface)) {
return false;
}
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();
+ interfaces1[i] = required[i].getName();
+ interfaces2[i] = descr.required[i].getName();
}
Arrays.sort(interfaces1);
return Arrays.equals(interfaces1, interfaces2);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public int hashCode() {
return required.hashCode();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
import java.util.List;
import java.util.Map;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class DefaultScope implements Scope {
- /**
- * DOCUMENT ME!
- */
private List<Scope> parents;
- /**
- * DOCUMENT ME!
- */
private Map<String, Object> properties;
- /**
- * DOCUMENT ME!
- */
private Map<String, Object> runtimes;
- /**
- * DOCUMENT ME!
- */
private Map<ProvidedInterface, ProvidedInterfaceImplementation> provided;
- /**
- * DOCUMENT ME!
- */
private List<ProvidedInterface> externallyProvided;
-/**
+ /**
* Creates a new DefaultScope object.
- *
- * @param aExternallyProvided DOCUMENT ME!
+ *
*/
public DefaultScope(List<ProvidedInterface> aExternallyProvided) {
this(aExternallyProvided.toArray(new ProvidedInterface[0]));
}
-/**
+ /**
* Creates a new DefaultScope object.
- *
- * @param aExternallyProvided DOCUMENT ME!
+ *
*/
public DefaultScope(ProvidedInterface[] aExternallyProvided) {
this(aExternallyProvided, new ArrayList<Scope>());
}
-/**
+ /**
* Creates a new DefaultScope object.
- *
- * @param aExternallyProvided DOCUMENT ME!
- * @param aParent DOCUMENT ME!
+ *
*/
public DefaultScope(ProvidedInterface[] aExternallyProvided, Scope aParent) {
this(aExternallyProvided, Arrays.asList(new Scope[] { aParent }));
}
-/**
+ /**
* Creates a new DefaultScope object.
- *
- * @param aExternallyProvided DOCUMENT ME!
- * @param aParent DOCUMENT ME!
+ *
*/
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>();
+ 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));
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public List<ProvidedInterface> getProvidedInterfaces() {
return Collections.unmodifiableList(externallyProvided);
}
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Object get(String aKey) {
return properties.get(aKey);
}
- /**
- * DOCUMENT ME!
- *
- * @param aKey DOCUMENT ME!
- * @param aValue DOCUMENT ME!
- */
@Override
public void put(String aKey, Object aValue) {
properties.put(aKey, aValue);
}
- /**
- * DOCUMENT ME!
- *
- * @param aComponent DOCUMENT ME!
- * @param aRuntime DOCUMENT ME!
- */
@Override
public void addRuntime(Component aComponent, Object aRuntime) {
runtimes.put(aComponent.getName(), aRuntime);
}
- /**
- * DOCUMENT ME!
- *
- * @param aComponent DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Object getRuntime(Component aComponent) {
return runtimes.get(aComponent.getName());
}
- /**
- * DOCUMENT ME!
- *
- * @param aName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Object getRuntime(String aName) {
return runtimes.get(aName);
}
- /**
- * DOCUMENT ME!
- *
- * @param aInterface DOCUMENT ME!
- * @param aImplementation DOCUMENT ME!
- */
@Override
synchronized public void publishInterface(ProvidedInterface aInterface,
Object aImplementation) {
- provided.put(aInterface,
- new ProvidedInterfaceImplementation(aInterface, aImplementation));
+ provided.put(aInterface, new ProvidedInterfaceImplementation(
+ aInterface, aImplementation));
}
- /**
- * DOCUMENT ME!
- *
- * @param <T> DOCUMENT ME!
- * @param aInterface DOCUMENT ME!
- * @param aType DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public <T> T getInterfaceImplementation(ProvidedInterface aInterface,
Class<T> aType) {
package org.wamblee.system.core;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision: 1.6 $
- */
+ */
public interface NamedInterface {
/**
* Name for the interface.
- *
- * @return DOCUMENT ME!
+ *
*/
String getName();
}
import java.util.Collection;
-
/**
- * Represents an interface provided by a component.
- * Different component objects should never share ProvidedInterface instances!
- *
+ * Represents an interface provided by a component. Different component objects
+ * should never share ProvidedInterface instances!
+ *
* @author Erik Brakkee
*/
public interface ProvidedInterface extends NamedInterface {
/**
* Returns the service type.
- *
+ *
* @return Service type.
*/
Class[] getInterfaceTypes();
/**
- * Determines whether the current provided interface exceeds the
- * given provided interface. In other words if it can provide at least
- * what the given provided interface can provide.
- *
- * @param aInterface Interface to compare to.
- *
+ * Determines whether the current provided interface exceeds the given
+ * provided interface. In other words if it can provide at least what the
+ * given provided interface can provide.
+ *
+ * @param aInterface
+ * Interface to compare to.
+ *
* @return True if the current interface exceeds the given provided
* interface.
*/
/**
* Represents a provided interface together with its implementation.
- *
+ *
* @author Erik Brakkee
*/
class ProvidedInterfaceImplementation {
- /**
- * DOCUMENT ME!
- */
private ProvidedInterface _provided;
- /**
- * DOCUMENT ME!
- */
private Object _implementation;
-/**
- * Constructs the object.
- * @param aProvided Provided interface.
- * @param aImplementation Implementation.
- */
+ /**
+ * Constructs the object.
+ *
+ * @param aProvided
+ * Provided interface.
+ * @param aImplementation
+ * Implementation.
+ */
public ProvidedInterfaceImplementation(ProvidedInterface aProvided,
Object aImplementation) {
- _provided = aProvided;
- _implementation = aImplementation;
+ _provided = aProvided;
+ _implementation = aImplementation;
}
/**
- * DOCUMENT ME!
- *
+ *
* @return The provided interface.
*/
public ProvidedInterface getProvided() {
}
/**
- * DOCUMENT ME!
- *
- * @param <T> Expected type of the implementation.
- * @param aType Type of the implementation.
- *
+ *
+ * @param <T>
+ * Expected type of the implementation.
+ * @param aType
+ * Type of the implementation.
+ *
* @return Implementation.
*/
public <T> T getImplementation(Class<T> aType) {
package org.wamblee.system.core;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision: 1.6 $
- */
+ */
public interface RequiredInterface extends NamedInterface {
/**
- * DOCUMENT ME!
- *
+ *
* @return True iff the required interface is optional.
*/
boolean isOptional();
/**
* Checks if the service is provided by a given provided interface.
- *
- * @param aInterface Provided interface.
- *
+ *
+ * @param aInterface
+ * Provided interface.
+ *
* @return
*/
boolean implementedBy(ProvidedInterface aInterface);
/**
* Sets the provider of this interface.
- *
- * @param aProvider Provider.
+ *
+ * @param aProvider
+ * Provider.
*/
void setProvider(ProvidedInterface aProvider);
/**
* Gets the provider interface.
- *
+ *
* @return Provider or null if not set.
*/
ProvidedInterface getProvider();
/**
- * Determines if the requirements of the current interface are at
- * least those of the given required interface.
- *
- * @param aInterface DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ * Determines if the requirements of the current interface are at least
+ * those of the given required interface.
+ *
+ *
*/
boolean covers(RequiredInterface aInterface);
}
import java.util.List;
-
/**
- * A scope represents a set of running services and the runtime information for the
- * started components and is (usually) the result of
- * starting a container.
+ * A scope represents a set of running services and the runtime information for
+ * the started components and is (usually) the result of starting a container.
*
* @author Erik Brakkee
*/
public interface Scope {
/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ * Gets the provided interfaces by this scope.
+ *
+ * @return Provided interfaces.
*/
-/**
- * Gets the provided interfaces by this scope.
- * @return Provided interfaces.
- */
List<ProvidedInterface> getProvidedInterfaces();
/**
* Adds a key value pair to the scope.
- *
- * @param aKey Key
- * @param aValue Value.
+ *
+ * @param aKey
+ * Key
+ * @param aValue
+ * Value.
*/
void put(String aKey, Object aValue);
/**
* Retrieves a value for the key.
- *
- * @param aKey Key.
- *
+ *
+ * @param aKey
+ * Key.
+ *
* @return Value.
*/
Object get(String aKey);
/**
* Adds the runtime of a started component.
- *
- * @param aComponent Component.
- * @param aRuntime Runtime.
+ *
+ * @param aComponent
+ * Component.
+ * @param aRuntime
+ * Runtime.
*/
void addRuntime(Component aComponent, Object aRuntime);
/**
* Publishes an implementation of a provided interface.
- *
- * @param aInterface Interface that is provided.
- * @param aImplementation Implementation of the interface.
+ *
+ * @param aInterface
+ * Interface that is provided.
+ * @param aImplementation
+ * Implementation of the interface.
*/
void publishInterface(ProvidedInterface aInterface, Object aImplementation);
- /**
- * DOCUMENT ME!
- *
- * @param <T> DOCUMENT ME!
- * @param aProvided DOCUMENT ME!
- * @param aType DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
<T> T getInterfaceImplementation(ProvidedInterface aProvided, Class<T> aType);
/**
* Gets the runtime for a component.
- *
- * @param aComponent Component for which we want to get the runtime.
- *
+ *
+ * @param aComponent
+ * Component for which we want to get the runtime.
+ *
* @return Runtime.
*/
Object getRuntime(Component aComponent);
/**
- * Gets the runtime for a component based on the name of the
- * component (excluding its context).
- *
- * @param aName Component name.
- *
+ * Gets the runtime for a component based on the name of the component
+ * (excluding its context).
+ *
+ * @param aName
+ * Component name.
+ *
* @return Component name.
*/
Object getRuntime(String aName);
/**
* Exception thrown when an error occurs in assembling the systems.
- *
+ *
* @author Erik Brakkee
*/
public class SystemAssemblyException extends RuntimeException {
-/**
- * Constructs the exception.
- * @param aMsg Message.
- */
+ /**
+ * Constructs the exception.
+ *
+ * @param aMsg
+ * Message.
+ */
public SystemAssemblyException(String aMsg) {
super(aMsg);
}
-/**
- * Constructs the exception.
- * @param aMsg Message
- * @param aCause Cause.
- */
+ /**
+ * Constructs the exception.
+ *
+ * @param aMsg
+ * Message
+ * @param aCause
+ * Cause.
+ */
public SystemAssemblyException(String aMsg, Throwable aCause) {
super(aMsg, aCause);
}
import java.util.ArrayList;
import java.util.List;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class CompositeEdgeFilter implements EdgeFilter {
- /**
- * DOCUMENT ME!
- */
private List<EdgeFilter> filters;
/**
filters = new ArrayList<EdgeFilter>();
}
- /**
- * DOCUMENT ME!
- *
- * @param aFilter DOCUMENT ME!
- */
public void add(EdgeFilter aFilter) {
filters.add(aFilter);
}
- /**
- * DOCUMENT ME!
- *
- * @param aEdge DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean isViolated(Edge aEdge) {
for (EdgeFilter filter : filters) {
package org.wamblee.system.graph;
/**
- * Represents an application-independent edge of a graph. Applications
- * might choose to implement the Edge interface directly.
- *
+ * Represents an application-independent edge of a graph. Applications might
+ * choose to implement the Edge interface directly.
+ *
* @author Erik Brakkee
*/
public class DefaultEdge implements Edge {
- /**
- * DOCUMENT ME!
- */
private Node from;
- /**
- * DOCUMENT ME!
- */
private Node to;
/**
* Creates a new DefaultEdge object.
- *
- * @param aFrom DOCUMENT ME!
- * @param aTo DOCUMENT ME!
+ *
*/
public DefaultEdge(Node aFrom, Node aTo) {
- from = aFrom;
- to = aTo;
+ from = aFrom;
+ to = aTo;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Node getFrom() {
return from;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Node getTo() {
return to;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return "Edge(" + from.getName() + ", " + to.getName() + ")";
/**
* Default application-independent node. Specific applications of the graph
* might implement the Node interface directly.
- *
+ *
* @author Erik Brakkee
*/
public class DefaultNode implements Node {
- /**
- * DOCUMENT ME!
- */
private String name;
-/**
- * Constructs the node.
- * @param aName Node name.
+ /**
+ * Constructs the node.
+ *
+ * @param aName
+ * Node name.
*/
public DefaultNode(String aName) {
name = aName;
/**
* Returns the node name.
- *
- * @return DOCUMENT ME!
+ *
*/
@Override
public String getName() {
return name;
}
- /**
- * DOCUMENT ME!
- *
- * @param aObj DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean equals(Object aObj) {
if (!(aObj instanceof Node)) {
return name.equals(node.getName());
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public int hashCode() {
return name.hashCode();
package org.wamblee.system.graph;
/**
- * Represents an edge of a graph.
+ * Represents an edge of a graph.
*
* @author Erik Brakkee
*/
public interface Edge {
/**
*
- DOCUMENT ME!
- *
+ *
* @return The from part of the edge.
*/
Node getFrom();
/**
*
- DOCUMENT ME!
- *
+ *
* @return The to part of the edge.
*/
Node getTo();
import java.util.List;
-
/**
- * Edge factory used to extend a graph with new edges.
+ * Edge factory used to extend a graph with new edges.
+ *
* @author Erik Brakkee
- *
- * @param <NodeType> Type of node.
+ *
+ * @param <NodeType>
+ * Type of node.
*/
public interface EdgeFactory<NodeType extends Node> {
/**
- * DOCUMENT ME!
- *
- * @param aFrom DOCUMENT ME!
- * @param aTo DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
-/**
- * Computes a number of new edges to be added to the graph.
- * @param aFrom From node.
- * @param aTo To node.
- * @return List of edges from the from to the to node.
+ * Computes a number of new edges to be added to the graph.
+ *
+ * @param aFrom
+ * From node.
+ * @param aTo
+ * To node.
+ * @return List of edges from the from to the to node.
*/
List<Edge> create(NodeType aFrom, NodeType aTo);
}
package org.wamblee.system.graph;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision: 1.6 $
- */
+ */
public interface EdgeFilter {
- /**
- * DOCUMENT ME!
- *
- * @param aEdge DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
boolean isViolated(Edge aEdge);
}
package org.wamblee.system.graph;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- *
- * @param <FromType> DOCUMENT ME!
- * @param <ToType> DOCUMENT ME!
+ *
*/
public class EdgeSelector<FromType extends Node, ToType extends Node> {
- /**
- * DOCUMENT ME!
- */
private Class<FromType> fromType;
- /**
- * DOCUMENT ME!
- */
private Class<ToType> toType;
/**
* Creates a new EdgeSelector object.
- *
- * @param aFrom DOCUMENT ME!
- * @param aTo DOCUMENT ME!
+ *
*/
public EdgeSelector(Class<FromType> aFrom, Class<ToType> aTo) {
- fromType = aFrom;
- toType = aTo;
+ fromType = aFrom;
+ toType = aTo;
}
- /**
- * DOCUMENT ME!
- *
- * @param aSelector DOCUMENT ME!
- * @param aEdge DOCUMENT ME!
- */
public void execute(Selector<FromType, ToType> aSelector, Edge aEdge) {
- if (fromType.isInstance(aEdge.getFrom())
- && toType.isInstance(aEdge.getTo())) {
- aSelector.execute((FromType) aEdge.getFrom(), (ToType) aEdge.getTo());
+ if (fromType.isInstance(aEdge.getFrom()) &&
+ toType.isInstance(aEdge.getTo())) {
+ aSelector.execute((FromType) aEdge.getFrom(), (ToType) aEdge
+ .getTo());
}
}
import java.util.Iterator;
import java.util.List;
-
/**
* Represents a graph consisting of nodes and edges.
- *
+ *
* @author Erik Brakkee
*/
public class Graph {
- /**
- * DOCUMENT ME!
- */
private List<Node> nodes;
- /**
- * DOCUMENT ME!
- */
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>();
}
/**
* Adds a node.
- *
- * @param aNode Node to add.
- *
- * @throws IllegalArgumentException In case the node already exists. Node
- * equality is checked using <code>equals</code>.
+ *
+ * @param aNode
+ * Node to add.
+ *
+ * @throws IllegalArgumentException
+ * In case the node already exists. Node equality is checked
+ * using <code>equals</code>.
*/
public void addNode(Node aNode) {
if (nodes.contains(aNode)) {
- throw new IllegalArgumentException("Node '" + aNode.getName()
- + "' already exists");
+ throw new IllegalArgumentException("Node '" + aNode.getName() +
+ "' already exists");
}
nodes.add(aNode);
/**
* Finds a node with the given name.
- *
- * @param aName Node name.
- *
+ *
+ * @param aName
+ * Node name.
+ *
* @return Node or null if not found.
*/
public Node findNode(String aName) {
/**
* Removes a node.
- *
- * @param aNode Node to remove.
- *
+ *
+ * @param aNode
+ * Node to remove.
+ *
* @return True iff the node was removed.
- *
- * @throws IllegalArgumentException In case there are edges of which the
- * node is a part.
+ *
+ * @throws IllegalArgumentException
+ * In case there are edges of which the node is a part.
*/
public boolean removeNode(Node aNode) {
if (!findOutgoing(aNode).isEmpty() || !findIncoming(aNode).isEmpty()) {
- throw new IllegalArgumentException("Cannot remove node '"
- + aNode.getName()
- + "' because it is connected to one or more edges");
+ throw new IllegalArgumentException("Cannot remove node '" +
+ aNode.getName() +
+ "' because it is connected to one or more edges");
}
return nodes.remove(aNode);
/**
* Adds a list of nodes.
- *
- * @param aNodes Nodes to add.
- *
+ *
+ * @param aNodes
+ * Nodes to add.
+ *
* @see #addNode(Node)
*/
public void addNodes(List<Node> aNodes) {
/**
* Adds an edge.
- *
- * @param aEdge Edge to add.
- *
- * @throws IllegalArgumentException In case one of the nodes of the edges
- * is not part of the graph or if the same edge (as determined by
- * {@link #equals(Object)} is already a part of the graph.
+ *
+ * @param aEdge
+ * Edge to add.
+ *
+ * @throws IllegalArgumentException
+ * In case one of the nodes of the edges is not part of the
+ * graph or if the same edge (as determined by
+ * {@link #equals(Object)} is already a part of the graph.
*/
public void addEdge(Edge aEdge) {
if (edges.contains(aEdge)) {
- throw new IllegalArgumentException("Edge '" + aEdge
- + "' already exists");
+ throw new IllegalArgumentException("Edge '" + aEdge +
+ "' already exists");
}
if (!nodes.contains(aEdge.getFrom())) {
- throw new IllegalArgumentException("From node '" + aEdge.getFrom()
- + "' from edge '" + aEdge + "' is not part of the graph");
+ throw new IllegalArgumentException("From node '" + aEdge.getFrom() +
+ "' from edge '" + aEdge + "' is not part of the graph");
}
if (!nodes.contains(aEdge.getTo())) {
- throw new IllegalArgumentException("To node '" + aEdge.getTo()
- + "' from edge '" + aEdge + "' is not part of the graph");
+ throw new IllegalArgumentException("To node '" + aEdge.getTo() +
+ "' from edge '" + aEdge + "' is not part of the graph");
}
edges.add(aEdge);
/**
* Removes an edge.
- *
- * @param aEdge Edge to remove.
- *
+ *
+ * @param aEdge
+ * Edge to remove.
+ *
* @return True if the edge was removed.
*/
public boolean removeEdge(Edge aEdge) {
/**
* Adds a number of edges.
- *
- * @param aEdges Edges to add.
+ *
+ * @param aEdges
+ * Edges to add.
*/
public void addEdges(List<Edge> aEdges) {
for (Edge edge : aEdges) {
/**
* Gets the nodes.
- *
+ *
* @return Copy of the list of nodes of the graph.
*/
public List<Node> getNodes() {
/**
* Gets the edges.
- *
+ *
* @return Copy of the list of edges of the graph.
*/
public List<Edge> getEdges() {
}
/**
- * Extends the graph with edges using an edge factory. All
- * combinations of nodes are passed to the factory which creates
- * additional edges.
- *
- * @param aFactory Edge factory.
+ * Extends the graph with edges using an edge factory. All combinations of
+ * nodes are passed to the factory which creates additional edges.
+ *
+ * @param aFactory
+ * Edge factory.
*/
public void extend(EdgeFactory aFactory) {
for (Node from : nodes) {
/**
* Applies a filter to the graph for removing elements.
- *
- * @param aFilter Filter to apply.
+ *
+ * @param aFilter
+ * Filter to apply.
*/
public void applyFilter(EdgeFilter aFilter) {
for (Iterator<Edge> edge = edges.iterator(); edge.hasNext();) {
}
/**
- * Finds all outgoing edges of a node. More specifically, finds
- * all edges <code>e</code> for which <code>e.getFrom().getName() =
+ * Finds all outgoing edges of a node. More specifically, finds all edges
+ * <code>e</code> for which <code>e.getFrom().getName() =
* aNode.getName()</code>.
- *
- * @param aNode Node for which to find outgoing edges.
- *
+ *
+ * @param aNode
+ * Node for which to find outgoing edges.
+ *
* @return List of outgoing edges.
*/
public List<Edge> findOutgoing(Node aNode) {
}
/**
- * Finds all incoming edges of a node. More specifically, finds
- * all edges <code>e</code> for which <code>e.getTo().getName() =
+ * Finds all incoming edges of a node. More specifically, finds all edges
+ * <code>e</code> for which <code>e.getTo().getName() =
* aNode.getName()</code>.
- *
- * @param aNode Node for which to find incoming edges.
- *
+ *
+ * @param aNode
+ * Node for which to find incoming edges.
+ *
* @return List of incoming edges.
*/
public List<Edge> findIncoming(Node aNode) {
}
/**
- * Implements a visitor design pattern. This loops over all nodes
- * and all edges and invokes the appropriate visit methods on the visitor.
- *
- * @param aVisitor Visitor.
+ * Implements a visitor design pattern. This loops over all nodes and all
+ * edges and invokes the appropriate visit methods on the visitor.
+ *
+ * @param aVisitor
+ * Visitor.
*/
public void accept(Visitor aVisitor) {
List<Node> nodes = getNodes(); // copy to make sure the visitor can
- // modify the
- // list of nodes as part of the loop.
+ // modify the
+ // list of nodes as part of the loop.
List<Edge> edges = getEdges(); // copy ..... (see above).
package org.wamblee.system.graph;
/**
- * Represents a node in a graph.
+ * Represents a node in a graph.
+ *
* @author Erik Brakkee
*/
public interface Node {
/**
* Gets the node name uniquely identifying the node in the graph.
- *
+ *
* @return Node name.
*/
String getName();
package org.wamblee.system.graph;
/**
- * Visitor of a graph.
+ * Visitor of a graph.
+ *
* @author Erik Brakkee.
- *
+ *
*/
public interface Visitor {
/**
* Visits a node. Called by {@link Graph#accept(Visitor)}.
- *
- * @param aNode Node to visit.
+ *
+ * @param aNode
+ * Node to visit.
*/
void visitNode(Node aNode);
/**
* Visits a node. Called by {@link Graph#accept(Visitor)}.
- *
- * @param aEdge Edge to visit.
+ *
+ * @param aEdge
+ * Edge to visit.
*/
void visitEdge(Edge aEdge);
}
import java.util.List;
-
/**
- * Visitor that checks whether all externally provided interfaces are
- * actually provided by any of the internal components.
- *
+ * Visitor that checks whether all externally provided interfaces are actually
+ * provided by any of the internal components.
+ *
* @author Erik Brakkee
*/
public class CheckExternallyProvidedVisitor implements Visitor {
- /**
- * DOCUMENT ME!
- */
private Graph graph;
-/**
- * Constructs the visitor.
- * @param aGraph Component graph.
+ /**
+ * Constructs the visitor.
+ *
+ * @param aGraph
+ * Component graph.
*/
public CheckExternallyProvidedVisitor(Graph aGraph) {
graph = aGraph;
}
- /**
- * DOCUMENT ME!
- *
- * @param aEdge DOCUMENT ME!
- */
@Override
public void visitEdge(Edge aEdge) {
// Empty.
}
- /**
- * DOCUMENT ME!
- *
- * @param aNode DOCUMENT ME!
- */
@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",
+ createDuplicateException(
+ "External provided interfaces has multiple internal matches",
aNode, edges);
}
if (edges.size() == 0) {
- throw new SystemAssemblyException(aNode
- + ": external provded interface is not provided by any of the internal components");
+ throw new SystemAssemblyException(
+ aNode +
+ ": external provded interface is not provided by any of the internal components");
}
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aMsg DOCUMENT ME!
- * @param aNode DOCUMENT ME!
- * @param edges DOCUMENT ME!
- */
private void createDuplicateException(String aMsg, Node aNode,
List<Edge> edges) {
StringBuffer buf = new StringBuffer();
import java.util.List;
-
/**
- * Visitor that checks whether all required external interfaces of the
- * container are provided.
- *
+ * Visitor that checks whether all required external interfaces of the container
+ * are provided.
+ *
* @author Erik Brakkee
*/
public class CheckExternallyRequiredVisitor implements Visitor {
- /**
- * DOCUMENT ME!
- */
private Log LOG = LogFactory.getLog(CheckExternallyRequiredVisitor.class);
- /**
- * DOCUMENT ME!
- */
private Graph graph;
/**
* Creates a new CheckExternallyRequiredVisitor object.
- *
- * @param aGraph DOCUMENT ME!
+ *
*/
public CheckExternallyRequiredVisitor(Graph aGraph) {
graph = aGraph;
}
- /**
- * DOCUMENT ME!
- *
- * @param aEdge DOCUMENT ME!
- */
@Override
public void visitEdge(Edge aEdge) {
// Empty.
}
- /**
- * DOCUMENT ME!
- *
- * @param aNode DOCUMENT ME!
- */
@Override
public void visitNode(Node aNode) {
if (aNode instanceof ExternalRequiredInterfaceNode) {
ExternalRequiredInterfaceNode required = (ExternalRequiredInterfaceNode) aNode;
- if (!required.getRequired().isOptional()
- && (required.getRequired().getProvider() == null)) {
- throw new SystemAssemblyException(aNode
- + ": External required interface is not provided");
+ if (!required.getRequired().isOptional() &&
+ (required.getRequired().getProvider() == null)) {
+ throw new SystemAssemblyException(aNode +
+ ": External required interface is not provided");
}
List<Edge> edges = graph.findIncoming(aNode);
RequiredInterfaceNode reqNode = (RequiredInterfaceNode) from;
- if (!reqNode.getRequired().isOptional()
- && required.getRequired().isOptional()) {
- throw new SystemAssemblyException(aNode
- + ": externally required interface is optional but a corresponding internal required interface is mandatory: "
- + reqNode);
+ if (!reqNode.getRequired().isOptional() &&
+ required.getRequired().isOptional()) {
+ throw new SystemAssemblyException(
+ aNode +
+ ": externally required interface is optional but a corresponding internal required interface is mandatory: " +
+ reqNode);
}
}
}
import java.util.List;
-
/**
* Visitor that checks whether required and provided interfaces are matched
* appropriately:
- * <ul>
- * <li>Each required interface is connected to at most one
- * provided interface</li>
- * <li>Required interfaces that are not optional must be connected
- * to precisely one provided interface</li>
- * </ul>
- *
+ * <ul>
+ * <li>Each required interface is connected to at most one provided interface</li>
+ * <li>Required interfaces that are not optional must be connected to precisely
+ * one provided interface</li>
+ * </ul>
+ *
* @author Erik Brakkee
*/
public class CheckRequiredProvidedMultiplicityVisitor implements Visitor {
- /**
- * DOCUMENT ME!
- */
private Graph graph;
/**
* Creates a new CheckRequiredProvidedMultiplicityVisitor object.
- *
- * @param aGraph DOCUMENT ME!
+ *
*/
public CheckRequiredProvidedMultiplicityVisitor(Graph aGraph) {
graph = aGraph;
}
- /**
- * DOCUMENT ME!
- *
- * @param aEdge DOCUMENT ME!
- */
@Override
public void visitEdge(Edge aEdge) {
// Empty
}
- /**
- * DOCUMENT ME!
- *
- * @param aNode DOCUMENT ME!
- */
@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);
+ createDuplicateException(
+ "Multiple providers of required interface found", aNode,
+ edges);
}
if ((edges.size() == 0) && !required.getRequired().isOptional()) {
- throw new SystemAssemblyException(aNode
- + ": mandatpory required interface not provided by other components started earlier");
+ throw new SystemAssemblyException(
+ aNode +
+ ": mandatpory required interface not provided by other components started earlier");
}
} else if (aNode instanceof ExternalProvidedInterfaceNode) {
List<Edge> edges = graph.findOutgoing(aNode);
if (edges.size() > 1) {
- createDuplicateException("multiple internal matches for externally provided interface",
+ createDuplicateException(
+ "multiple internal matches for externally provided interface",
aNode, edges);
}
if (edges.size() == 0) {
- throw new SystemAssemblyException(aNode
- + ": external provided interface is not provided internally");
+ throw new SystemAssemblyException(aNode +
+ ": external provided interface is not provided internally");
}
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aMsg DOCUMENT ME!
- * @param aNode DOCUMENT ME!
- * @param edges DOCUMENT ME!
- */
private void createDuplicateException(String aMsg, Node aNode,
List<Edge> edges) {
StringBuffer buf = new StringBuffer();
import java.util.ArrayList;
import java.util.List;
-
/**
- * Checks whether the given component graph can be started in component
- * order without any missing dependencies.
- *
+ * Checks whether the given component graph can be started in component order
+ * without any missing dependencies.
+ *
* @author Erik Brakkee
*/
public class CheckStartupDependenciesVisitor implements Visitor {
- /**
- * DOCUMENT ME!
- */
private Graph graph;
- /**
- * DOCUMENT ME!
- */
private List<Node> available;
-/**
- * Constructs the visitor.
- * @param aGraph Graph.
+ /**
+ * Constructs the visitor.
+ *
+ * @param aGraph
+ * Graph.
*/
public CheckStartupDependenciesVisitor(Graph aGraph) {
- graph = aGraph;
- available = new ArrayList<Node>();
+ graph = aGraph;
+ available = new ArrayList<Node>();
}
- /**
- * DOCUMENT ME!
- *
- * @param aEdge DOCUMENT ME!
- */
@Override
public void visitEdge(Edge aEdge) {
// Empty
}
- /**
- * DOCUMENT ME!
- *
- * @param aNode DOCUMENT ME!
- */
@Override
public void visitNode(Node aNode) {
List<Edge> edges = graph.findOutgoing(aNode);
Node dep = edge.getTo();
if (!available.contains(dep)) {
- throw new SystemAssemblyException(aNode
- + ": required dependency '" + dep + "' was not started");
+ throw new SystemAssemblyException(aNode +
+ ": required dependency '" + dep + "' was not started");
}
}
import java.util.ArrayList;
import java.util.List;
-
/**
- * Represents a component graph and provides the bridge from the component
- * model to a graph model. The graph model is easier to work with to implement
- * specific actions and validations than the component model.
+ * Represents a component graph and provides the bridge from the component model
+ * to a graph model. The graph model is easier to work with to implement
+ * specific actions and validations than the component model.
*/
public class ComponentGraph extends Graph {
- /**
- * DOCUMENT ME!
- */
private boolean isLinked;
- /**
- * DOCUMENT ME!
- */
private CompositeEdgeFilter edgeFilter;
-/**
- * Constructs an empty component graph.
+ /**
+ * Constructs an empty component graph.
*/
public ComponentGraph() {
- isLinked = false;
- edgeFilter = new CompositeEdgeFilter();
+ isLinked = false;
+ edgeFilter = new CompositeEdgeFilter();
}
/**
- * Adds an externally required interface of a container. This
- * should be called before any components of the container are added.
- *
- * @param aComponent Component requiring the interface.
- * @param aInterface Required interface.
+ * Adds an externally required interface of a container. This should be
+ * called before any components of the container are added.
+ *
+ * @param aComponent
+ * Component requiring the interface.
+ * @param aInterface
+ * Required interface.
*/
public void addRequiredInterface(Component aComponent,
RequiredInterface aInterface) {
}
/**
- * Adds an externally provided interface of a container. This
- * should be called after all components of the container have been added.
- *
- * @param aComponent Component providing the interface.
- * @param aInterface Provided interface.
+ * Adds an externally provided interface of a container. This should be
+ * called after all components of the container have been added.
+ *
+ * @param aComponent
+ * Component providing the interface.
+ * @param aInterface
+ * Provided interface.
*/
public void addProvidedInterface(Component aComponent,
ProvidedInterface aInterface) {
}
/**
- * Links provided and required interfaces together in the component
- * model based on the graph model.
+ * Links provided and required interfaces together in the component model
+ * based on the graph model.
*/
public void link() {
if (isLinked) {
}
/**
- * Finds a list of mappings of external provided interface to
- * internal provided interface.
- *
+ * Finds a list of mappings of external provided interface to internal
+ * provided interface.
+ *
* @return List of pairs of external to internal interface.
*/
public List<Pair<ProvidedInterface, ProvidedInterface>> findExternalProvidedInterfaceMapping() {
List<Pair<ProvidedInterface, ProvidedInterface>> result = new ArrayList<Pair<ProvidedInterface, ProvidedInterface>>();
for (Edge edge : getEdges()) {
- if (edge.getFrom() instanceof ExternalProvidedInterfaceNode
- && edge.getTo() instanceof ProvidedInterfaceNode) {
+ if (edge.getFrom() instanceof ExternalProvidedInterfaceNode &&
+ edge.getTo() instanceof ProvidedInterfaceNode) {
result.add(new Pair<ProvidedInterface, ProvidedInterface>(
- ((ExternalProvidedInterfaceNode) edge.getFrom())
- .getProvided(),
- ((ProvidedInterfaceNode) edge.getTo()).getProvided()));
+ ((ExternalProvidedInterfaceNode) edge.getFrom())
+ .getProvided(), ((ProvidedInterfaceNode) edge.getTo())
+ .getProvided()));
}
}
}
/**
- * Adds a component by adding required interfaces, components, and
- * provided interfaces.
- *
- * @param aComponent Component to add.
+ * Adds a component by adding required interfaces, components, and provided
+ * interfaces.
+ *
+ * @param aComponent
+ * Component to add.
*/
public void addComponent(Component<?> aComponent) {
- // Add required interfaces.
- Node compNode = new ComponentNode(aComponent);
+ // Add required interfaces.
+ Node compNode = new ComponentNode(aComponent);
List<Node> requiredNodes = new ArrayList<Node>();
for (RequiredInterface required : aComponent.getRequiredInterfaces()) {
// Add the component
addNode(compNode);
- // Edges from component to required interface.
+ // Edges from component to required interface.
for (Node reqNode : requiredNodes) {
addEdge(new DefaultEdge(compNode, reqNode));
}
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aEdgeFilter DOCUMENT ME!
- */
public void addEdgeFilter(CompositeEdgeFilter aEdgeFilter) {
edgeFilter.add(aEdgeFilter);
}
import org.wamblee.system.core.Component;
import org.wamblee.system.graph.Node;
-
/**
* Represents a component node.
- *
+ *
* @author Erik Brakkee.
*/
public class ComponentNode implements Node {
- /**
- * DOCUMENT ME!
- */
private Component<?> component;
/**
* Creates a new ComponentNode object.
- *
- * @param aComponent DOCUMENT ME!
+ *
*/
public ComponentNode(Component<?> aComponent) {
component = aComponent;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getName() {
return component.getQualifiedName();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Component<?> getComponent() {
return component;
}
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.EdgeFilter;
-
/**
- * Filter used to explicitly connect required and provided interfaces
- * within a container.
- *
+ * Filter used to explicitly connect required and provided interfaces within a
+ * container.
+ *
* @author Erik Brakkee
*/
public class ConnectExternalProvidedProvidedFilter implements EdgeFilter {
- /**
- * DOCUMENT ME!
- */
private String externalProvided;
- /**
- * DOCUMENT ME!
- */
private String component;
- /**
- * DOCUMENT ME!
- */
private String provided;
/**
* Creates a new ConnectExternalProvidedProvidedFilter object.
- *
- * @param aExternalProvided DOCUMENT ME!
- * @param aComponent DOCUMENT ME!
- * @param aProvided DOCUMENT ME!
+ *
*/
public ConnectExternalProvidedProvidedFilter(String aExternalProvided,
String aComponent, String aProvided) {
- externalProvided = aExternalProvided;
- component = aComponent;
- provided = aProvided;
+ externalProvided = aExternalProvided;
+ component = aComponent;
+ provided = aProvided;
if (externalProvided == null) {
throw new IllegalArgumentException(
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aEdge DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean isViolated(Edge aEdge) {
- if (aEdge.getFrom() instanceof ExternalProvidedInterfaceNode
- && aEdge.getTo() instanceof ProvidedInterfaceNode) {
+ if (aEdge.getFrom() instanceof ExternalProvidedInterfaceNode &&
+ aEdge.getTo() instanceof ProvidedInterfaceNode) {
return isViolated((ExternalProvidedInterfaceNode) aEdge.getFrom(),
(ProvidedInterfaceNode) aEdge.getTo());
}
return false;
}
- /**
- * DOCUMENT ME!
- *
- * @param aFrom DOCUMENT ME!
- * @param aTo DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private boolean isViolated(ExternalProvidedInterfaceNode aFrom,
ProvidedInterfaceNode aTo) {
if (!aFrom.getName().equals(externalProvided)) {
return false; // wrong provided interface.
}
- if (aTo.getComponent().getName().equals(component)
- && aTo.getProvided().getName().equals(provided)) {
- return false; // ok
+ if (aTo.getComponent().getName().equals(component) &&
+ aTo.getProvided().getName().equals(provided)) {
+ return false; // ok
}
return true;
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.EdgeFilter;
-
/**
- * Filter used to explicitly connect required and provided interfaces
- * within a container.
- *
+ * Filter used to explicitly connect required and provided interfaces within a
+ * container.
+ *
* @author Erik Brakkee
*/
public class ConnectRequiredExternallyRequiredEdgeFilter implements EdgeFilter {
- /**
- * DOCUMENT ME!
- */
private String client;
- /**
- * DOCUMENT ME!
- */
private String required;
- /**
- * DOCUMENT ME!
- */
private String externalRequired;
/**
* Creates a new ConnectRequiredExternallyRequiredEdgeFilter object.
- *
- * @param aClient DOCUMENT ME!
- * @param aRequired DOCUMENT ME!
- * @param aExternalRequired DOCUMENT ME!
+ *
*/
public ConnectRequiredExternallyRequiredEdgeFilter(String aClient,
String aRequired, String aExternalRequired) {
- client = aClient;
- required = aRequired;
- externalRequired = aExternalRequired;
+ client = aClient;
+ required = aRequired;
+ externalRequired = aExternalRequired;
if (client == null) {
throw new IllegalArgumentException(
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aEdge DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean isViolated(Edge aEdge) {
- if (aEdge.getFrom() instanceof RequiredInterfaceNode
- && aEdge.getTo() instanceof ExternalRequiredInterfaceNode) {
+ if (aEdge.getFrom() instanceof RequiredInterfaceNode &&
+ aEdge.getTo() instanceof ExternalRequiredInterfaceNode) {
return isViolated((RequiredInterfaceNode) aEdge.getFrom(),
(ExternalRequiredInterfaceNode) aEdge.getTo());
}
return false;
}
- /**
- * DOCUMENT ME!
- *
- * @param aFrom DOCUMENT ME!
- * @param aTo DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private boolean isViolated(RequiredInterfaceNode aFrom,
ExternalRequiredInterfaceNode aTo) {
if (!aFrom.getComponent().getName().equals(client)) {
- return false; // wrong component.
+ 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)) {
- return true; // wrong externally required interface.
+ return true; // wrong externally required interface.
}
return false;
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.EdgeFilter;
-
/**
- * Filter used to explicitly connect required and provided interfaces
- * within a container.
- *
+ * Filter used to explicitly connect required and provided interfaces within a
+ * container.
+ *
* @author Erik Brakkee
*/
public class ConnectRequiredProvidedEdgeFilter implements EdgeFilter {
- /**
- * DOCUMENT ME!
- */
private String client;
- /**
- * DOCUMENT ME!
- */
private String required;
- /**
- * DOCUMENT ME!
- */
private String server;
- /**
- * DOCUMENT ME!
- */
private String provided;
/**
* Creates a new ConnectRequiredProvidedEdgeFilter object.
- *
- * @param aClient DOCUMENT ME!
- * @param aRequired DOCUMENT ME!
- * @param aServer DOCUMENT ME!
- * @param aProvided DOCUMENT ME!
+ *
*/
public ConnectRequiredProvidedEdgeFilter(String aClient, String aRequired,
String aServer, String aProvided) {
- client = aClient;
- required = aRequired;
- server = aServer;
- provided = aProvided;
+ client = aClient;
+ required = aRequired;
+ server = aServer;
+ provided = aProvided;
if (client == null) {
throw new IllegalArgumentException(
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aEdge DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean isViolated(Edge aEdge) {
- if (aEdge.getFrom() instanceof RequiredInterfaceNode
- && aEdge.getTo() instanceof ProvidedInterfaceNode) {
+ if (aEdge.getFrom() instanceof RequiredInterfaceNode &&
+ aEdge.getTo() instanceof ProvidedInterfaceNode) {
return isViolated((RequiredInterfaceNode) aEdge.getFrom(),
(ProvidedInterfaceNode) aEdge.getTo());
}
return false;
}
- /**
- * DOCUMENT ME!
- *
- * @param aFrom DOCUMENT ME!
- * @param aTo DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private boolean isViolated(RequiredInterfaceNode aFrom,
ProvidedInterfaceNode aTo) {
- if (client.equals(aFrom.getComponent().getName())
- && ((required == null)
- || required.equals(aFrom.getRequired().getName()))) {
+ if (client.equals(aFrom.getComponent().getName()) &&
+ ((required == null) || required.equals(aFrom.getRequired()
+ .getName()))) {
// From part matches.
if (server == null) {
return true; // all connections are eliminated
}
- if (server.equals(aTo.getComponent().getName())
- && ((provided == null)
- || provided.equals(aTo.getProvided().getName()))) {
+ if (server.equals(aTo.getComponent().getName()) &&
+ ((provided == null) || provided.equals(aTo.getProvided()
+ .getName()))) {
// to part matches also
return false;
} else {
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.graph.Node;
-
/**
* Represents an external provided interface of a container.
- *
+ *
* @author Erik Brakkee
*/
public class ExternalProvidedInterfaceNode implements Node {
- /**
- * DOCUMENT ME!
- */
private Component component;
- /**
- * DOCUMENT ME!
- */
private ProvidedInterface provided;
/**
* Creates a new ExternalProvidedInterfaceNode object.
- *
- * @param aComponent DOCUMENT ME!
- * @param aProvided DOCUMENT ME!
+ *
*/
public ExternalProvidedInterfaceNode(Component aComponent,
ProvidedInterface aProvided) {
- component = aComponent;
- provided = aProvided;
+ component = aComponent;
+ provided = aProvided;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getName() {
return provided.getName();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Component getComponent() {
return component;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public ProvidedInterface getProvided() {
return provided;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return component.getQualifiedName() + ":" + provided;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.graph.Node;
-
/**
* Represents an externally required interface of a container.
- *
+ *
* @author Erik Brakkee
*/
public class ExternalRequiredInterfaceNode implements Node {
- /**
- * DOCUMENT ME!
- */
private Component component;
- /**
- * DOCUMENT ME!
- */
private RequiredInterface required;
/**
* Creates a new ExternalRequiredInterfaceNode object.
- *
- * @param aComponent DOCUMENT ME!
- * @param aRequired DOCUMENT ME!
+ *
*/
public ExternalRequiredInterfaceNode(Component aComponent,
RequiredInterface aRequired) {
- component = aComponent;
- required = aRequired;
+ component = aComponent;
+ required = aRequired;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getName() {
return required.getName();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Component getComponent() {
return component;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public RequiredInterface getRequired() {
return required;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return component.getQualifiedName() + ":" + required;
import org.wamblee.system.graph.Node;
import org.wamblee.system.graph.Visitor;
-
/**
* Visitor that creates links between required and provided interfaces as
- * described by the edges in the graph. Specically it links together (1)
- * required and provided interfaces of internal component of a container and
- * (2) the providers of externally required interfaces and internal required
+ * described by the edges in the graph. Specically it links together (1)
+ * required and provided interfaces of internal component of a container and (2)
+ * the providers of externally required interfaces and internal required
* interfaces.
- *
+ *
* @author Erik Brakkee
*/
public class LinkVisitor implements Visitor {
- /**
- * DOCUMENT ME!
- *
- * @param aEdge DOCUMENT ME!
- */
@Override
public void visitEdge(Edge aEdge) {
Node from = aEdge.getFrom();
- Node to = aEdge.getTo();
+ Node to = aEdge.getTo();
if (from instanceof RequiredInterfaceNode) {
RequiredInterfaceNode required = (RequiredInterfaceNode) from;
required.getRequired().setProvider(provided.getProvided());
} else if (to instanceof ExternalRequiredInterfaceNode) {
ExternalRequiredInterfaceNode external = (ExternalRequiredInterfaceNode) to;
- ProvidedInterface provider = external.getRequired()
+ ProvidedInterface provider = external.getRequired()
.getProvider();
if ((provider == null) && !required.getRequired().isOptional()) {
- throw new SystemAssemblyException("Mandatory interface '"
- + from + "' is not provided.");
+ throw new SystemAssemblyException("Mandatory interface '" +
+ from + "' is not provided.");
}
if (provider != null) {
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aNode DOCUMENT ME!
- */
@Override
public void visitNode(Node aNode) {
// Empty.
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.graph.Node;
-
/**
* Provided interface node.
- *
+ *
* @author Erik Brakkee
*/
public class ProvidedInterfaceNode implements Node {
- /**
- * DOCUMENT ME!
- */
private Component component;
- /**
- * DOCUMENT ME!
- */
private ProvidedInterface provided;
/**
* Creates a new ProvidedInterfaceNode object.
- *
- * @param aComponent DOCUMENT ME!
- * @param aProvided DOCUMENT ME!
+ *
*/
public ProvidedInterfaceNode(Component aComponent,
ProvidedInterface aProvided) {
- component = aComponent;
- provided = aProvided;
+ component = aComponent;
+ provided = aProvided;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getName() {
return component.getQualifiedName() + ":" + provided.getName();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public ProvidedInterface getProvided() {
return provided;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Component getComponent() {
return component;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return component.getQualifiedName() + ":" + provided;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.graph.Node;
-
/**
* Required interface node.
- *
+ *
* @author Erik Brakkee
*/
public class RequiredInterfaceNode implements Node {
- /**
- * DOCUMENT ME!
- */
private Component component;
- /**
- * DOCUMENT ME!
- */
private RequiredInterface required;
/**
* Creates a new RequiredInterfaceNode object.
- *
- * @param aComponent DOCUMENT ME!
- * @param aRequired DOCUMENT ME!
+ *
*/
public RequiredInterfaceNode(Component aComponent,
RequiredInterface aRequired) {
- component = aComponent;
- required = aRequired;
+ component = aComponent;
+ required = aRequired;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getName() {
return component.getQualifiedName() + ":" + required.getName();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public RequiredInterface getRequired() {
return required;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Component getComponent() {
return component;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String toString() {
return component.getQualifiedName() + ":" + required;
import java.util.ArrayList;
import java.util.List;
-
/**
* Factory that creates edges between required and provided interfaces.
* Speciflcally it creates:
- * <ul>
- * <li>Edges between provided and required interfaces of a
- * container.</li>
- * <li>Edges between required and externally required interfaces</li>
- * <li>Edges between externally provided and provided interfaces.
- * </ul>
- *
+ * <ul>
+ * <li>Edges between provided and required interfaces of a container.</li>
+ * <li>Edges between required and externally required interfaces</li>
+ * <li>Edges between externally provided and provided interfaces.
+ * </ul>
+ *
* @author Erik Brakkee
*/
public class RequiredProvidedEdgeFactory implements EdgeFactory {
// Empty.
}
- /**
- * DOCUMENT ME!
- *
- * @param aFrom DOCUMENT ME!
- * @param aTo DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public List<Edge> create(Node aFrom, Node aTo) {
List<Edge> result = new ArrayList<Edge>();
if (aTo instanceof ProvidedInterfaceNode) {
ProvidedInterfaceNode provided = (ProvidedInterfaceNode) aTo;
- if (required.getRequired().implementedBy(provided.getProvided())) {
+ if (required.getRequired()
+ .implementedBy(provided.getProvided())) {
result.add(new DefaultEdge(required, provided));
}
} else if (aTo instanceof ExternalRequiredInterfaceNode) {
import org.wamblee.system.core.Component;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
+
import org.wamblee.test.EventTracker;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class AdapterTestCase extends TestCase {
- /**
- * DOCUMENT ME!
- */
static EventTracker<String> EVENT_TRACKER;
- /**
- * DOCUMENT ME!
- */
protected Scope scope;
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
super.setUp();
- EVENT_TRACKER = new EventTracker<String>();
- scope = new DefaultScope(new ProvidedInterface[0]);
+ EVENT_TRACKER = new EventTracker<String>();
+ scope = new DefaultScope(new ProvidedInterface[0]);
}
}
import org.wamblee.test.AssertionUtils;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class ClassAdapterTest extends AdapterTestCase {
- /**
- * DOCUMENT ME!
- */
public void testSimpleConstructorInjection() {
ClassConfiguration x1Config = new ClassConfiguration(X1.class);
x1Config.getObjectConfig().getSetterConfig().initAllSetters();
ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config);
ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
- Container container = new Container("top",
- new Component[] { x1Adapter, x4Adapter },
- new ProvidedInterface[0], new RequiredInterface[0]);
+ Container container = new Container("top", new Component[] { x1Adapter,
+ x4Adapter }, new ProvidedInterface[0], new RequiredInterface[0]);
- Scope scope = container.start();
+ Scope scope = container.start();
AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)" },
EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
assertSame(x1, x4.getX1());
}
- /**
- * DOCUMENT ME!
- */
public void testConstructorAndSetterInjection() {
ClassConfiguration x1Config = new ClassConfiguration(X1.class);
x1Config.getObjectConfig().getSetterConfig().initAllSetters();
ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
ClassAdapter x8Adapter = new ClassAdapter("x8", x8Config);
- Container container = new Container("top",
- new Component[] { x1Adapter, x4Adapter, x8Adapter },
- new ProvidedInterface[0], new RequiredInterface[0]);
+ Container container = new Container("top", new Component[] { x1Adapter,
+ x4Adapter, x8Adapter }, new ProvidedInterface[0],
+ new RequiredInterface[0]);
- Scope scope = container.start();
- AssertionUtils.assertEquals(new String[] {
- "x1(hello)", "x4(x1)", "x8(x1)", "x8.setX4(x4)"
- }, EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+ Scope scope = container.start();
+ AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)",
+ "x8(x1)", "x8.setX4(x4)" }, EVENT_TRACKER.getEvents(
+ Thread.currentThread()).toArray());
Object obj1 = scope.getRuntime(x1Adapter);
assertTrue(obj1 instanceof X1);
Object obj8 = scope.getRuntime(x8Adapter);
- X1 x1 = (X1) obj1;
- X4 x4 = (X4) obj4;
- X8 x8 = (X8) obj8;
+ X1 x1 = (X1) obj1;
+ X4 x4 = (X4) obj4;
+ X8 x8 = (X8) obj8;
assertSame(x4, x8.getX4());
assertSame(x1, x8.getX1());
import java.util.Collections;
import java.util.List;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class ClassConfigurationTest extends AdapterTestCase {
- /**
- * DOCUMENT ME!
- */
public void testConstructorConfig() {
- ClassConfiguration classConfig = new ClassConfiguration(X1.class);
+ ClassConfiguration classConfig = new ClassConfiguration(X1.class);
- ConstructorConfiguration config = classConfig.getConstructorConfig()
+ ConstructorConfiguration config = classConfig.getConstructorConfig()
.greedy();
- ProvidedInterface provided = new DefaultProvidedInterface("arg",
- String.class);
- List<RequiredInterface> required = classConfig.getRequiredInterfaces();
+ ProvidedInterface provided = new DefaultProvidedInterface("arg",
+ String.class);
+ List<RequiredInterface> required = classConfig.getRequiredInterfaces();
assertEquals(1, required.size());
assertFalse(required.get(0).isOptional());
AssertionUtils.assertEquals(new String[] { "x1(hello)" },
AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
- .toArray());
+ .toArray());
}
- /**
- * DOCUMENT ME!
- */
public void testConstructorConfigWithSetters() {
ClassConfiguration classConfig = new ClassConfiguration(X7.class);
classConfig.getConstructorConfig().select(Boolean.class);
classConfig.getObjectConfig().getSetterConfig().initAllSetters()
- .values("setPort").setValue(0, 10);
-
- ProvidedInterface providedBoolean = new DefaultProvidedInterface("boolean",
- Boolean.class);
- ProvidedInterface providedHost = new DefaultProvidedInterface("host",
- String.class);
- List<RequiredInterface> required = classConfig
- .getRequiredInterfaces();
+ .values("setPort").setValue(0, 10);
+
+ ProvidedInterface providedBoolean = new DefaultProvidedInterface(
+ "boolean", Boolean.class);
+ ProvidedInterface providedHost = new DefaultProvidedInterface("host",
+ String.class);
+ List<RequiredInterface> required = classConfig.getRequiredInterfaces();
Collections.sort(required, new RequiredInterfaceComparator());
assertEquals(2, required.size());
import java.util.List;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class ConstructorConfigurationTest extends AdapterTestCase {
- /**
- * DOCUMENT ME!
- */
public void testGreedyUnique() {
- ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
+ ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
.greedy();
- ProvidedInterface provided = new DefaultProvidedInterface("arg",
- String.class);
- List<RequiredInterface> required = config.getRequiredInterfaces();
+ ProvidedInterface provided = new DefaultProvidedInterface("arg",
+ String.class);
+ List<RequiredInterface> required = config.getRequiredInterfaces();
assertEquals(1, required.size());
assertFalse(required.get(0).isOptional());
AssertionUtils.assertEquals(new String[] { "x1(hello)" },
AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
- .toArray());
+ .toArray());
}
- /**
- * DOCUMENT ME!
- */
public void testGreedyNonUnique() {
try {
- ConstructorConfiguration config = new ConstructorConfiguration(X2.class)
- .greedy();
+ ConstructorConfiguration config = new ConstructorConfiguration(
+ X2.class).greedy();
} catch (SystemAssemblyException e) {
// e.printStackTrace();
return;
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testSpecificConstructor() {
- ConstructorConfiguration config = new ConstructorConfiguration(X2.class)
+ ConstructorConfiguration config = new ConstructorConfiguration(X2.class)
.select(String.class);
- ProvidedInterface provided = new DefaultProvidedInterface("arg",
- String.class);
- List<RequiredInterface> required = config.getRequiredInterfaces();
+ ProvidedInterface provided = new DefaultProvidedInterface("arg",
+ String.class);
+ List<RequiredInterface> required = config.getRequiredInterfaces();
assertEquals(1, required.size());
required.get(0).setProvider(provided);
AssertionUtils.assertEquals(new String[] { "x2(hello)" },
AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
- .toArray());
+ .toArray());
}
- /**
- * DOCUMENT ME!
- */
public void testSetValue() {
ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
.greedy();
AssertionUtils.assertEquals(new String[] { "x1(bla)" },
AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
- .toArray());
+ .toArray());
}
- /**
- * DOCUMENT ME!
- */
public void testOptionalValueProvided() {
ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
.greedy();
config.getParameters().setOptional(0);
- ProvidedInterface provided = new DefaultProvidedInterface("arg",
- String.class);
+ ProvidedInterface provided = new DefaultProvidedInterface("arg",
+ String.class);
List<RequiredInterface> required = config.getRequiredInterfaces();
assertEquals(1, required.size());
AssertionUtils.assertEquals(new String[] { "x1(hello)" },
AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
- .toArray());
+ .toArray());
}
- /**
- * DOCUMENT ME!
- */
public void testOptionalValueMissing() {
ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
.greedy();
AssertionUtils.assertEquals(new String[] { "x1(null)" },
AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
- .toArray());
+ .toArray());
}
- /**
- * DOCUMENT ME!
- */
public void testIgnoredNonPublic() {
- ConstructorConfiguration config = new ConstructorConfiguration(X3.class)
+ ConstructorConfiguration config = new ConstructorConfiguration(X3.class)
.greedy();
- List<RequiredInterface> required = config.getRequiredInterfaces();
+ List<RequiredInterface> required = config.getRequiredInterfaces();
assertEquals(0, config.getParameters().getTypes().length);
}
- /**
- * DOCUMENT ME!
- */
public void testNonPublicConstructor() {
- ConstructorConfiguration config = new ConstructorConfiguration(X3.class).setNonPublic(true)
- .greedy();
- ProvidedInterface provided = new DefaultProvidedInterface("arg",
- String.class);
- List<RequiredInterface> required = config.getRequiredInterfaces();
+ ConstructorConfiguration config = new ConstructorConfiguration(X3.class)
+ .setNonPublic(true).greedy();
+ ProvidedInterface provided = new DefaultProvidedInterface("arg",
+ String.class);
+ List<RequiredInterface> required = config.getRequiredInterfaces();
assertEquals(1, required.size());
assertFalse(required.get(0).isOptional());
AssertionUtils.assertEquals(new String[] { "x3(hello)" },
AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
- .toArray());
+ .toArray());
}
}
import org.wamblee.test.AssertionUtils;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class DefaultContainerTest extends AdapterTestCase {
- /**
- * DOCUMENT ME!
- */
public void testConstructorInjection() {
ClassConfiguration x1Config = new ClassConfiguration(X1.class);
x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
ClassConfiguration x4Config = new ClassConfiguration(X4.class);
x4Config.getObjectConfig().getSetterConfig().initAllSetters();
- DefaultContainer container = new DefaultContainer("top").addComponent("x1",
- x1Config).addComponent("x4", x4Config);
+ DefaultContainer container = new DefaultContainer("top").addComponent(
+ "x1", x1Config).addComponent("x4", x4Config);
- Scope scope = container.start();
+ Scope scope = container.start();
AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)" },
EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
assertTrue(obj instanceof X4);
}
- /**
- * DOCUMENT ME!
- */
public void testConstructorInjectionAndSetterInjection() {
ClassConfiguration x1Config = new ClassConfiguration(X1.class);
x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
ObjectConfiguration x8Config = new ObjectConfiguration(X8.class);
x8Config.getSetterConfig().initAllSetters();
- DefaultContainer container = new DefaultContainer("top").addComponent("x1",
- x1Config).addComponent("x4", x4Config)
- .addComponent("x8", x8, x8Config);
+ DefaultContainer container = new DefaultContainer("top").addComponent(
+ "x1", x1Config).addComponent("x4", x4Config).addComponent("x8", x8,
+ x8Config);
- Scope scope = container.start();
- AssertionUtils.assertEquals(new String[] {
- "x1(hello)", "x4(x1)", "x8.setX4(x4)"
- }, EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+ Scope scope = container.start();
+ AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)",
+ "x8.setX4(x4)" }, EVENT_TRACKER.getEvents(Thread.currentThread())
+ .toArray());
Object obj1 = scope.getRuntime("x1");
assertTrue(obj1 instanceof X1);
assertSame(obj4, x8.getX4());
}
- /**
- * DOCUMENT ME!
- */
public void testWrongObjectType() {
final DefaultContainer container = new DefaultContainer("top");
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.addComponent("x", "y",
- new ObjectConfiguration(Integer.class));
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ container.addComponent("x", "y", new ObjectConfiguration(
+ Integer.class));
+ }
+ }, IllegalArgumentException.class);
}
}
import java.util.Collections;
import java.util.List;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class ObjectAdapterTest extends AdapterTestCase {
- /**
- * DOCUMENT ME!
- */
public void testSetterInjection() {
ClassConfiguration x1Config = new ClassConfiguration(X1.class);
x1Config.getObjectConfig().getSetterConfig().initAllSetters();
ObjectConfiguration x8Config = new ObjectConfiguration(X8.class);
x8Config.getSetterConfig().initAllSetters();
- X1 x1 = new X1();
- X8 x8 = new X8(x1);
+ X1 x1 = new X1();
+ X8 x8 = new X8(x1);
- ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config);
- ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
+ ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config);
+ ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
ObjectAdapter x8Adapter = new ObjectAdapter("x8", x8, x8Config);
- Container container = new Container("top",
- new Component[] { x1Adapter, x4Adapter, x8Adapter },
- new ProvidedInterface[0], new RequiredInterface[0]);
+ Container container = new Container("top", new Component[] { x1Adapter,
+ x4Adapter, x8Adapter }, new ProvidedInterface[0],
+ new RequiredInterface[0]);
EVENT_TRACKER.clear();
Scope scope = container.start();
- AssertionUtils.assertEquals(new String[] {
- "x1(hello)", "x4(x1)", "x8.setX4(x4)"
- }, EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+ AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)",
+ "x8.setX4(x4)" }, EVENT_TRACKER.getEvents(Thread.currentThread())
+ .toArray());
Object obj1 = scope.getRuntime(x1Adapter);
assertTrue(obj1 instanceof X1);
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class SetterConfigurationTest extends AdapterTestCase {
- /**
- * DOCUMENT ME!
- */
public void testOneSetter() {
SetterConfiguration config = new SetterConfiguration(X5.class);
config.initAllSetters();
assertEquals("setValue.0", required.get(0).getName());
ProvidedInterface provided = new DefaultProvidedInterface("janse",
- String.class);
+ String.class);
required.get(0).setProvider(provided);
scope.publishInterface(provided, "hello");
assertEquals("hello", obj.getValue());
}
- /**
- * DOCUMENT ME!
- */
public void testPrivateSetter() {
SetterConfiguration config = new SetterConfiguration(X5.class);
config.setNonPublic(true);
config.initAllSetters();
- List<RequiredInterface> required = new ArrayList<RequiredInterface>(config
- .getRequiredInterfaces());
- Collections.sort(required,
- new Comparator<RequiredInterface>() {
- @Override
- public int compare(RequiredInterface aO1, RequiredInterface aO2) {
- return aO1.getName().compareTo(aO2.getName());
- }
- });
+ List<RequiredInterface> required = new ArrayList<RequiredInterface>(
+ config.getRequiredInterfaces());
+ Collections.sort(required, new Comparator<RequiredInterface>() {
+ @Override
+ public int compare(RequiredInterface aO1, RequiredInterface aO2) {
+ return aO1.getName().compareTo(aO2.getName());
+ }
+ });
assertEquals(2, required.size());
assertEquals("setValue.0", required.get(0).getName());
assertEquals("setXyz.0", required.get(1).getName());
- ProvidedInterface providedString = new DefaultProvidedInterface("janse",
- String.class);
+ ProvidedInterface providedString = new DefaultProvidedInterface(
+ "janse", String.class);
assertTrue(required.get(0).implementedBy(providedString));
required.get(0).setProvider(providedString);
scope.publishInterface(providedString, "hello");
ProvidedInterface providedInt = new DefaultProvidedInterface("xxx",
- Integer.class);
+ Integer.class);
assertTrue(required.get(1).implementedBy(providedInt));
required.get(1).setProvider(providedInt);
scope.publishInterface(providedInt, 100);
assertEquals(100, obj.getXyz().intValue());
}
- /**
- * DOCUMENT ME!
- */
public void testInheritance() {
SetterConfiguration config = new SetterConfiguration(X9.class);
config.setNonPublic(true);
config.initAllSetters();
- List<RequiredInterface> required = new ArrayList<RequiredInterface>(config
- .getRequiredInterfaces());
- Collections.sort(required,
- new Comparator<RequiredInterface>() {
- @Override
- public int compare(RequiredInterface aO1, RequiredInterface aO2) {
- return aO1.getName().compareTo(aO2.getName());
- }
- });
+ List<RequiredInterface> required = new ArrayList<RequiredInterface>(
+ config.getRequiredInterfaces());
+ Collections.sort(required, new Comparator<RequiredInterface>() {
+ @Override
+ public int compare(RequiredInterface aO1, RequiredInterface aO2) {
+ return aO1.getName().compareTo(aO2.getName());
+ }
+ });
assertEquals(3, required.size());
assertEquals("setFlag.0", required.get(0).getName());
assertEquals("setValue.0", required.get(1).getName());
assertEquals("setXyz.0", required.get(2).getName());
- ProvidedInterface providedBoolean = new DefaultProvidedInterface("janse",
- Boolean.class);
+ ProvidedInterface providedBoolean = new DefaultProvidedInterface(
+ "janse", Boolean.class);
assertTrue(required.get(0).implementedBy(providedBoolean));
required.get(0).setProvider(providedBoolean);
scope.publishInterface(providedBoolean, true);
- ProvidedInterface providedString = new DefaultProvidedInterface("janse",
- String.class);
+ ProvidedInterface providedString = new DefaultProvidedInterface(
+ "janse", String.class);
assertTrue(required.get(1).implementedBy(providedString));
required.get(1).setProvider(providedString);
scope.publishInterface(providedString, "hello");
ProvidedInterface providedInt = new DefaultProvidedInterface("xxx",
- Integer.class);
+ Integer.class);
assertTrue(required.get(2).implementedBy(providedInt));
required.get(2).setProvider(providedInt);
scope.publishInterface(providedInt, 100);
assertTrue(obj.isFlag());
}
- /**
- * DOCUMENT ME!
- */
public void testMultipleSetters() {
- SetterConfiguration config = new SetterConfiguration(X6.class)
+ SetterConfiguration config = new SetterConfiguration(X6.class)
.initAllSetters();
List<RequiredInterface> required = config.getRequiredInterfaces();
Collections.sort(required, new RequiredInterfaceComparator());
assertEquals("setPort.0", required.get(1).getName());
ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
- String.class);
+ String.class);
required.get(0).setProvider(provided0);
scope.publishInterface(provided0, "hello");
ProvidedInterface provided1 = new DefaultProvidedInterface("port",
- Integer.class);
+ Integer.class);
required.get(1).setProvider(provided1);
scope.publishInterface(provided1, 10);
assertEquals(10, obj.getPort().intValue());
}
- /**
- * DOCUMENT ME!
- */
public void testInvokeWrongType() {
- final SetterConfiguration config = new SetterConfiguration(X5.class)
+ final SetterConfiguration config = new SetterConfiguration(X5.class)
.initAllSetters();
- List<RequiredInterface> required = config.getRequiredInterfaces();
+ List<RequiredInterface> required = config.getRequiredInterfaces();
assertEquals(1, required.size());
assertEquals("setValue.0", required.get(0).getName());
ProvidedInterface provided = new DefaultProvidedInterface("janse",
- String.class);
+ String.class);
required.get(0).setProvider(provided);
scope.publishInterface(provided, "hello");
final X6 obj = new X6();
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.inject(scope, obj);
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ config.inject(scope, obj);
+ }
+ }, IllegalArgumentException.class);
}
- /**
- * DOCUMENT ME!
- */
public void testSetExplicitValue() {
SetterConfiguration config = new SetterConfiguration(X5.class)
.initAllSetters();
assertEquals("bladibla", obj.getValue());
}
- /**
- * DOCUMENT ME!
- */
public void testClear() {
SetterConfiguration config = new SetterConfiguration(X6.class);
config.clear();
assertNull(obj.getPort());
}
- /**
- * DOCUMENT ME!
- */
public void testAddByName() {
SetterConfiguration config = new SetterConfiguration(X6.class);
config.clear().add("setHost");
assertEquals("setHost.0", required.get(0).getName());
ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
- String.class);
+ String.class);
required.get(0).setProvider(provided0);
scope.publishInterface(provided0, "hello");
assertNull(obj.getPort());
}
- /**
- * DOCUMENT ME!
- */
public void testAddByType() {
SetterConfiguration config = new SetterConfiguration(X6.class);
config.clear().addSetter(String.class);
assertEquals("setHost.0", required.get(0).getName());
ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
- String.class);
+ String.class);
required.get(0).setProvider(provided0);
scope.publishInterface(provided0, "hello");
assertNull(obj.getPort());
}
- /**
- * DOCUMENT ME!
- */
public void testAddPrivate() {
- X5 obj = new X5();
+ X5 obj = new X5();
final SetterConfiguration config = new SetterConfiguration(X5.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.add("xyz");
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ config.add("xyz");
+ }
+ }, IllegalArgumentException.class);
config.setNonPublic(true);
config.clear();
assertEquals(1, config.getRequiredInterfaces().size());
}
- /**
- * DOCUMENT ME!
- */
public void testAddNonExisting() {
final SetterConfiguration config = new SetterConfiguration(X6.class);
config.clear();
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.add("bladibla");
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ config.add("bladibla");
+ }
+ }, IllegalArgumentException.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.addSetter(DataSource.class);
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ config.addSetter(DataSource.class);
+ }
+ }, IllegalArgumentException.class);
}
- /**
- * DOCUMENT ME!
- */
public void testAddByTypeNonUnique() {
final SetterConfiguration config = new SetterConfiguration(X11.class);
config.clear();
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.addSetter(String.class);
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ config.addSetter(String.class);
+ }
+ }, IllegalArgumentException.class);
}
- /**
- * DOCUMENT ME!
- */
public void testRemove() {
SetterConfiguration config = new SetterConfiguration(X6.class)
.initAllSetters();
assertEquals("setHost.0", required.get(0).getName());
ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
- String.class);
+ String.class);
required.get(0).setProvider(provided0);
scope.publishInterface(provided0, "hello");
assertNull(obj.getPort());
}
- /**
- * DOCUMENT ME!
- *
- * @throws NoSuchMethodException DOCUMENT ME!
- */
public void testRemoveByMethodObject() throws NoSuchMethodException {
SetterConfiguration config = new SetterConfiguration(X6.class)
.initAllSetters();
assertEquals("setHost.0", required.get(0).getName());
ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
- String.class);
+ String.class);
required.get(0).setProvider(provided0);
scope.publishInterface(provided0, "hello");
assertNull(obj.getPort());
}
- /**
- * DOCUMENT ME!
- */
public void testRemoveNonExisting() {
final SetterConfiguration config = new SetterConfiguration(X6.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.remove("bladibla");
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ config.remove("bladibla");
+ }
+ }, IllegalArgumentException.class);
}
- /**
- * DOCUMENT ME!
- */
public void testOverridingSetters() {
SetterConfiguration config = new SetterConfiguration(X10.class)
.initAllSetters();
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X1 {
/**
* Creates a new X1 object.
/**
* Creates a new X1 object.
- *
- * @param aValue DOCUMENT ME!
+ *
*/
public X1(String aValue) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x1(" + aValue + ")");
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X10 extends X6 {
- /**
- * DOCUMENT ME!
- *
- * @param aHost DOCUMENT ME!
- */
@Override
public void setHost(String aHost) {
super.setHost(aHost);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getHost() {
return super.getHost();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Integer getPort() {
return super.getPort();
}
- /**
- * DOCUMENT ME!
- *
- * @param aPort DOCUMENT ME!
- */
@Override
public void setPort(Integer aPort) {
super.setPort(aPort);
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X11 {
- /**
- * DOCUMENT ME!
- *
- * @param aValue DOCUMENT ME!
- */
public void setX(String aValue) {
}
- /**
- * DOCUMENT ME!
- *
- * @param aValue DOCUMENT ME!
- */
public void setY(String aValue) {
}
}
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X2 {
/**
* Creates a new X2 object.
- *
- * @param aInteger DOCUMENT ME!
+ *
*/
public X2(Integer aInteger) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aInteger + ")");
/**
* Creates a new X2 object.
- *
- * @param aValue DOCUMENT ME!
+ *
*/
public X2(String aValue) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aValue + ")");
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X3 {
/**
* Creates a new X3 object.
/**
* Creates a new X3 object.
- *
- * @param aValue DOCUMENT ME!
+ *
*/
protected X3(String aValue) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x3(" + aValue + ")");
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X4 {
- /**
- * DOCUMENT ME!
- */
private X1 x1;
/**
* Creates a new X4 object.
- *
- * @param aX1 DOCUMENT ME!
+ *
*/
public X4(X1 aX1) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x4(x1)");
x1 = aX1;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public X1 getX1() {
return x1;
}
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X5 {
- /**
- * DOCUMENT ME!
- */
private String value;
- /**
- * DOCUMENT ME!
- */
private Integer xyz;
/**
public X5() {
}
- /**
- * DOCUMENT ME!
- *
- * @param aValue DOCUMENT ME!
- */
public void setValue(String aValue) {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x5.setValue(" + aValue
- + ")");
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x5.setValue(" + aValue +
+ ")");
value = aValue;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String getValue() {
return value;
}
- /**
- * DOCUMENT ME!
- */
public void doSomething() {
// Empty.
}
- /**
- * DOCUMENT ME!
- *
- * @param aXyz DOCUMENT ME!
- */
private void setXyz(int aXyz) {
xyz = aXyz;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Integer getXyz() {
return xyz;
}
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X6 {
- /**
- * DOCUMENT ME!
- */
private String host;
- /**
- * DOCUMENT ME!
- */
private Integer port;
/**
public X6() {
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Integer getPort() {
return port;
}
- /**
- * DOCUMENT ME!
- *
- * @param aPort DOCUMENT ME!
- */
public void setPort(Integer aPort) {
port = aPort;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String getHost() {
return host;
}
- /**
- * DOCUMENT ME!
- *
- * @param aHost DOCUMENT ME!
- */
public void setHost(String aHost) {
host = aHost;
}
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X7 {
- /**
- * DOCUMENT ME!
- */
private String host;
- /**
- * DOCUMENT ME!
- */
private Integer port;
- /**
- * DOCUMENT ME!
- */
private Boolean flag;
/**
* Creates a new X7 object.
- *
- * @param aBoolean DOCUMENT ME!
+ *
*/
public X7(Boolean aBoolean) {
flag = aBoolean;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Boolean getBoolean() {
return flag;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Integer getPort() {
return port;
}
- /**
- * DOCUMENT ME!
- *
- * @param aPort DOCUMENT ME!
- */
public void setPort(Integer aPort) {
port = aPort;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String getHost() {
return host;
}
- /**
- * DOCUMENT ME!
- *
- * @param aHost DOCUMENT ME!
- */
public void setHost(String aHost) {
host = aHost;
}
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X8 {
- /**
- * DOCUMENT ME!
- */
private X1 x1;
- /**
- * DOCUMENT ME!
- */
private X4 x4;
/**
* Creates a new X8 object.
- *
- * @param aX1 DOCUMENT ME!
+ *
*/
public X8(X1 aX1) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x8(x1)");
x1 = aX1;
}
- /**
- * DOCUMENT ME!
- *
- * @param aX4 DOCUMENT ME!
- */
public void setX4(X4 aX4) {
AdapterTestCase.EVENT_TRACKER.eventOccurred("x8.setX4(x4)");
x4 = aX4;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public X4 getX4() {
return x4;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public X1 getX1() {
return x1;
}
package org.wamblee.system.adapters;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class X9 extends X5 {
- /**
- * DOCUMENT ME!
- */
private boolean flag;
/**
public X9() {
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public boolean isFlag() {
return flag;
}
- /**
- * DOCUMENT ME!
- *
- * @param aFlag DOCUMENT ME!
- */
public void setFlag(boolean aFlag) {
flag = aFlag;
}
import java.util.Properties;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class DatabaseComponent extends AbstractComponent<Database> {
- /**
- * DOCUMENT ME!
- */
- private static ProvidedInterface DB_PROPS = new DefaultProvidedInterface("dbProps",
- Properties.class);
+ private static ProvidedInterface DB_PROPS = new DefaultProvidedInterface(
+ "dbProps", Properties.class);
- /**
- * DOCUMENT ME!
- */
private Database database;
/**
* Creates a new DatabaseComponent object.
- *
- * @param aName DOCUMENT ME!
- * @param aDatabase DOCUMENT ME!
+ *
*/
public DatabaseComponent(String aName, Database aDatabase) {
super(aName);
addProvidedInterface(DB_PROPS);
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Database doStart(Scope aScope) {
database.start();
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.driver", database.getDriverClassName());
props.put("database.url", database.getJdbcUrl());
props.put("database.username", database.getUsername());
props.put("database.password", database.getPassword());
return database;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
protected void doStop(Database aRuntime) {
database.stop();
import org.wamblee.system.container.Container;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class DatabaseComponentFactory {
- /**
- * DOCUMENT ME!
- *
- * @param aContainer DOCUMENT ME!
- */
public static void addDatabaseConfig(Container aContainer) {
try {
- aContainer.addComponent(new DatabaseComponent("db",
- DatabaseBuilder.getDatabase()));
+ aContainer.addComponent(new DatabaseComponent("db", DatabaseBuilder
+ .getDatabase()));
} catch (Exception e) {
- throw new RuntimeException("Could not add database configuration", e);
+ throw new RuntimeException("Could not add database configuration",
+ e);
}
}
}
import org.wamblee.test.EventTracker;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class Application extends AbstractComponent<Object> {
- /**
- * DOCUMENT ME!
- */
private EventTracker<String> tracker;
- /**
- * DOCUMENT ME!
- */
private String string;
- /**
- * DOCUMENT ME!
- */
private Integer integer;
- /**
- * DOCUMENT ME!
- */
private double random;
/**
/**
* Creates a new Application object.
- *
- * @param aName DOCUMENT ME!
+ *
*/
public Application(String aName) {
this(aName, "");
/**
* Creates a new Application object.
- *
- * @param aName DOCUMENT ME!
- * @param aPrefix DOCUMENT ME!
+ *
*/
public Application(String aName, String aPrefix) {
super(aName, new ProvidedInterface[0], required(false, aPrefix));
/**
* Creates a new Application object.
- *
- * @param aIsOptinal DOCUMENT ME!
+ *
*/
public Application(boolean aIsOptinal) {
super("application", new ProvidedInterface[0], required(true, ""));
/**
* Creates a new Application object.
- *
- * @param aTracker DOCUMENT ME!
+ *
*/
public Application(EventTracker<String> aTracker) {
this();
tracker = aTracker;
}
- /**
- * DOCUMENT ME!
- *
- * @param aOptional DOCUMENT ME!
- * @param aPrefix DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public static RequiredInterface[] required(boolean aOptional, String aPrefix) {
return new RequiredInterface[] {
new DefaultRequiredInterface(aPrefix + "string", String.class,
aOptional),
new DefaultRequiredInterface(aPrefix + "integer", Integer.class,
- aOptional)
- };
+ aOptional) };
}
- /**
- * DOCUMENT ME!
- *
- * @param aOptional DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public static RequiredInterface[] required(boolean aOptional) {
return required(aOptional, "");
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Object doStart(Scope aScope) {
track("start." + getName());
- string = aScope.getInterfaceImplementation(getRequiredInterfaces()
- .get(0).getProvider(), String.class);
- integer = aScope.getInterfaceImplementation(getRequiredInterfaces()
- .get(1).getProvider(), Integer.class);
+ string = aScope.getInterfaceImplementation(getRequiredInterfaces().get(
+ 0).getProvider(), String.class);
+ integer = aScope.getInterfaceImplementation(getRequiredInterfaces()
+ .get(1).getProvider(), Integer.class);
return random;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String getString() {
return string;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Integer getInteger() {
return integer;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
public void doStop(Object aRuntime) {
track("stop." + getName());
if (random != (Double) aRuntime) {
- throw new IllegalArgumentException("Wrong runtime: expected "
- + random + " but got " + aRuntime);
+ throw new IllegalArgumentException("Wrong runtime: expected " +
+ random + " but got " + aRuntime);
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aString DOCUMENT ME!
- */
private void track(String aString) {
if (tracker == null) {
return;
import java.util.ArrayList;
import java.util.List;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class ContainerTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
private EventTracker<String> tracker;
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
super.setUp();
tracker = new EventTracker<String>();
}
- /**
- * DOCUMENT ME!
- *
- * @param aProvided DOCUMENT ME!
- * @param aProvider DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private List<Pair<ProvidedInterface, Component>> createProvidedInput(
ProvidedInterface[] aProvided, Component aProvider) {
List<Pair<ProvidedInterface, Component>> result = new ArrayList<Pair<ProvidedInterface, Component>>();
for (ProvidedInterface provided : aProvided) {
result.add(new Pair<ProvidedInterface, Component>(provided,
- aProvider));
+ aProvider));
}
return result;
}
- /**
- * DOCUMENT ME!
- */
public void testEnvironmentApplication() {
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();
+ 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(Thread.currentThread()).toArray(new String[0]));
+ AssertionUtils.assertEquals(new String[] { "start.environment",
+ "start.application" }, tracker.getEvents(Thread.currentThread())
+ .toArray(new String[0]));
assertEquals(0, scope.getProvidedInterfaces().size());
assertEquals(environment.getString(), application.getString());
assertEquals(environment.getInteger(), application.getInteger());
}
- /**
- * DOCUMENT ME!
- */
public void testEnvironmentApplicationSimpleConstructor() {
Environment environment = new Environment(tracker);
Application application = new Application(tracker);
- Container container = new Container("root").addComponent(environment)
+ Container container = new Container("root").addComponent(environment)
.addComponent(application);
- Scope scope = container.start();
- AssertionUtils.assertEquals(new String[] {
- "start.environment", "start.application"
- }, tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ Scope scope = container.start();
+ AssertionUtils.assertEquals(new String[] { "start.environment",
+ "start.application" }, tracker.getEvents(Thread.currentThread())
+ .toArray(new String[0]));
assertEquals(0, scope.getProvidedInterfaces().size());
assertEquals(environment.getString(), application.getString());
assertEquals(environment.getInteger(), application.getInteger());
}
- /**
- * DOCUMENT ME!
- */
public void testApplicationEnvironment() {
try {
Component<?> environment = new Environment();
Component<?> application = new Application();
- Container container = new Container("root",
- new Component[] { application, environment },
- new ProvidedInterface[0], new RequiredInterface[0]);
+ Container container = new Container("root", new Component[] {
+ application, environment }, new ProvidedInterface[0],
+ new RequiredInterface[0]);
container.start();
} catch (SystemAssemblyException e) {
// e.printStackTrace();
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testComposite() {
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], new RequiredInterface[0]);
- Scope runtime = system.start();
+ Container system = new Container("all", new Component[] { environment,
+ application }, new ProvidedInterface[0], new RequiredInterface[0]);
+ Scope runtime = system.start();
List<RequiredInterface> required = system.getRequiredInterfaces();
assertEquals(0, required.size());
List<ProvidedInterface> provided = system.getProvidedInterfaces();
assertEquals(0, provided.size());
- AssertionUtils.assertEquals(new String[] {
- "start.environment", "start.application"
- }, tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ AssertionUtils.assertEquals(new String[] { "start.environment",
+ "start.application" }, tracker.getEvents(Thread.currentThread())
+ .toArray(new String[0]));
tracker.clear();
system.stop(runtime);
- AssertionUtils.assertEquals(new String[] {
- "stop.application", "stop.environment"
- }, tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ AssertionUtils.assertEquals(new String[] { "stop.application",
+ "stop.environment" }, tracker.getEvents(Thread.currentThread())
+ .toArray(new String[0]));
}
- /**
- * DOCUMENT ME!
- */
public void testCompositeWithWrongProvidedInfo() {
try {
Component<?> environment = new Environment();
Component<?> application = new Application();
- Container system = new Container("all",
- new Component[] { environment, application },
- new ProvidedInterface[] {
- new DefaultProvidedInterface("float", Float.class)
- }, new DefaultRequiredInterface[0]);
+ Container system = new Container("all", new Component[] {
+ environment, application },
+ new ProvidedInterface[] { new DefaultProvidedInterface("float",
+ Float.class) }, new DefaultRequiredInterface[0]);
system.validate();
} catch (SystemAssemblyException e) {
return;
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testCompositeRequiredInterfaceNotProvided() {
try {
Component<?> environment = new Environment();
Component<?> application = new Application();
- Container system = new Container("all",
- new Component[] { environment, application },
- new ProvidedInterface[0],
- new RequiredInterface[] {
- new DefaultRequiredInterface("string", String.class)
- });
+ Container system = new Container("all", new Component[] {
+ environment, application }, new ProvidedInterface[0],
+ new RequiredInterface[] { new DefaultRequiredInterface(
+ "string", String.class) });
system.start();
} catch (SystemAssemblyException e) {
return;
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testCompositeWithSuperfluousRequiredInfo() {
Component<?> environment = new Environment();
Component<?> application = new Application();
- Container system = new Container("all",
- new Component[] { environment, application },
- new ProvidedInterface[0],
- new RequiredInterface[] {
- new DefaultRequiredInterface("float", Float.class)
- });
- system.getRequiredInterfaces().get(0)
- .setProvider(new DefaultProvidedInterface("hallo", Float.class));
+ Container system = new Container("all", new Component[] { environment,
+ application }, new ProvidedInterface[0],
+ new RequiredInterface[] { new DefaultRequiredInterface("float",
+ Float.class) });
+ system.getRequiredInterfaces().get(0).setProvider(
+ new DefaultProvidedInterface("hallo", Float.class));
system.start();
List<RequiredInterface> required = system.getRequiredInterfaces();
assertEquals(0, provided.size());
}
- /**
- * DOCUMENT ME!
- */
public void testCompositeWithExternalDependencesNotProvided() {
try {
Component<?> application = new Application();
- Container system = new Container("all",
- new Component[] { application }, new ProvidedInterface[0],
- application.getRequiredInterfaces()
- .toArray(new RequiredInterface[0]));
+ Container system = new Container("all",
+ new Component[] { application }, new ProvidedInterface[0],
+ application.getRequiredInterfaces().toArray(
+ new RequiredInterface[0]));
system.start();
} catch (SystemAssemblyException e) {
return;
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testDuplicateComponent() {
try {
- Component<?> comp1 = new Application();
- Component<?> comp2 = new Application();
- Container system = new Container("top");
+ Component<?> comp1 = new Application();
+ Component<?> comp2 = new Application();
+ Container system = new Container("top");
system.addComponent(comp1).addComponent(comp2);
} catch (SystemAssemblyException e) {
return;
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testInconsistentHierarchy() {
try {
- Component<?> comp = new Application();
- Container system = new Container("top").addComponent(comp);
- Container system2 = new Container("top2").addComponent(comp);
+ Component<?> comp = new Application();
+ Container system = new Container("top").addComponent(comp);
+ Container system2 = new Container("top2").addComponent(comp);
} catch (SystemAssemblyException e) {
return;
}
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testCompositeWithExternalDependencesProvided() {
Component<?> environment = new Environment();
Component<?> application = new Application();
- Container system = new Container("all",
- new Component[] { application }, new ProvidedInterface[0],
- application.getRequiredInterfaces()
- .toArray(new RequiredInterface[0]));
+ Container system = new Container("all",
+ new Component[] { application }, new ProvidedInterface[0],
+ application.getRequiredInterfaces().toArray(
+ new RequiredInterface[0]));
environment.start(new DefaultScope(new ProvidedInterface[0]));
- system.getRequiredInterfaces().get(0)
- .setProvider(environment.getProvidedInterfaces().get(0));
- system.getRequiredInterfaces().get(1)
- .setProvider(environment.getProvidedInterfaces().get(1));
+ system.getRequiredInterfaces().get(0).setProvider(
+ environment.getProvidedInterfaces().get(0));
+ system.getRequiredInterfaces().get(1).setProvider(
+ environment.getProvidedInterfaces().get(1));
system.start();
assertEquals(0, provided.size());
}
- /**
- * DOCUMENT ME!
- */
public void testAmbiguousInterfaces() {
try {
Component<?> environment1 = new Environment();
Component<?> environment2 = new Environment();
- Component<?> application = new Application();
- Container container = new Container("root",
- new Component[] { environment1, environment2, application },
- new ProvidedInterface[0], new RequiredInterface[0]);
+ Component<?> application = new Application();
+ Container container = new Container("root", new Component[] {
+ environment1, environment2, application },
+ new ProvidedInterface[0], new RequiredInterface[0]);
container.start();
} catch (SystemAssemblyException e) {
return;
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testIncompleteRequirements() {
try {
Component<?> application = new Application();
- Container system = new Container("all",
- new Component[] { application }, new ProvidedInterface[0],
- new RequiredInterface[0]);
+ Container system = new Container("all",
+ new Component[] { application }, new ProvidedInterface[0],
+ new RequiredInterface[0]);
system.start();
} catch (SystemAssemblyException e) {
return;
fail();
}
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- * @throws RuntimeException DOCUMENT ME!
- */
public void testEnvironmentApplicationRollbackOnException()
throws Exception {
Environment environment = new Environment(tracker);
Application application = new Application() {
- @Override
- public Object doStart(Scope aScope) {
- throw new RuntimeException();
- }
- };
+ @Override
+ public Object doStart(Scope aScope) {
+ throw new RuntimeException();
+ }
+ };
try {
- Container container = new Container("root",
- new Component[] { environment, application },
- new ProvidedInterface[0], new RequiredInterface[0]);
+ Container container = new Container("root", new Component[] {
+ environment, application }, new ProvidedInterface[0],
+ new RequiredInterface[0]);
container.start();
} catch (RuntimeException e) {
- AssertionUtils.assertEquals(new String[] {
- "start.environment", "stop.environment"
- },
- tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ AssertionUtils.assertEquals(new String[] { "start.environment",
+ "stop.environment" }, tracker.getEvents(Thread.currentThread())
+ .toArray(new String[0]));
return;
}
fail();
}
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- * @throws RuntimeException DOCUMENT ME!
- */
public void testEnvironmentApplicationRollbackOnExceptionWithExceptionOnStop()
throws Exception {
Environment environment = new Environment(tracker);
// Application 1 will throw an exception while stopping.
Application application1 = new Application("app1") {
- @Override
- public void doStop(Object aRuntime) {
- throw new RuntimeException();
- }
- };
+ @Override
+ public void doStop(Object aRuntime) {
+ throw new RuntimeException();
+ }
+ };
// application 2 will throw an exception while starting
Application application2 = new Application("app2") {
- public Object doStart(Scope aScope) {
- throw new RuntimeException();
- }
- };
+ public Object doStart(Scope aScope) {
+ throw new RuntimeException();
+ }
+ };
try {
- Container container = new Container("root",
- new Component[] { environment, application1, application2 },
- new ProvidedInterface[0], new RequiredInterface[0]);
+ Container container = new Container("root", new Component[] {
+ environment, application1, application2 },
+ new ProvidedInterface[0], new RequiredInterface[0]);
container.start();
} catch (RuntimeException e) {
- AssertionUtils.assertEquals(new String[] {
- "start.environment", "stop.environment"
- },
- tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ AssertionUtils.assertEquals(new String[] { "start.environment",
+ "stop.environment" }, tracker.getEvents(Thread.currentThread())
+ .toArray(new String[0]));
return;
}
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testOptionalRequiredInterfaceProvidedOptionalInternal() {
Application application = new Application(true);
- Container container = new Container("top",
- new Component[] { application }, new ProvidedInterface[0],
- Application.required(true));
- Environment env = new Environment();
- container.getRequiredInterfaces().get(0)
- .setProvider(env.getProvidedInterfaces().get(0));
- container.getRequiredInterfaces().get(1)
- .setProvider(env.getProvidedInterfaces().get(1));
+ Container container = new Container("top",
+ new Component[] { application }, new ProvidedInterface[0],
+ Application.required(true));
+ Environment env = new Environment();
+ container.getRequiredInterfaces().get(0).setProvider(
+ env.getProvidedInterfaces().get(0));
+ container.getRequiredInterfaces().get(1).setProvider(
+ env.getProvidedInterfaces().get(1));
Scope external = new DefaultScope(env.getProvidedInterfaces());
env.start(external);
container.start(external);
- assertSame(env.getProvidedInterfaces().get(0),
- container.getRequiredInterfaces().get(0).getProvider());
- assertSame(env.getProvidedInterfaces().get(1),
- container.getRequiredInterfaces().get(1).getProvider());
- assertSame(env.getProvidedInterfaces().get(0),
- application.getRequiredInterfaces().get(0).getProvider());
- assertSame(env.getProvidedInterfaces().get(1),
- application.getRequiredInterfaces().get(1).getProvider());
- }
-
- /**
- * DOCUMENT ME!
- */
+ assertSame(env.getProvidedInterfaces().get(0), container
+ .getRequiredInterfaces().get(0).getProvider());
+ assertSame(env.getProvidedInterfaces().get(1), container
+ .getRequiredInterfaces().get(1).getProvider());
+ assertSame(env.getProvidedInterfaces().get(0), application
+ .getRequiredInterfaces().get(0).getProvider());
+ assertSame(env.getProvidedInterfaces().get(1), application
+ .getRequiredInterfaces().get(1).getProvider());
+ }
+
public void testOptionalRequiredInterfaceNotProvidedOptionalInternal() {
Application application = new Application(true);
- Container container = new Container("top",
- new Component[] { application }, new ProvidedInterface[0],
- Application.required(true));
- Environment env = new Environment();
- container.getRequiredInterfaces().get(0)
- .setProvider(env.getProvidedInterfaces().get(0));
+ Container container = new Container("top",
+ new Component[] { application }, new ProvidedInterface[0],
+ Application.required(true));
+ Environment env = new Environment();
+ container.getRequiredInterfaces().get(0).setProvider(
+ env.getProvidedInterfaces().get(0));
Scope external = new DefaultScope(new ProvidedInterface[0]);
- external.publishInterface(env.getProvidedInterfaces().get(0),
- env.getString());
+ external.publishInterface(env.getProvidedInterfaces().get(0), env
+ .getString());
container.start(external);
- assertSame(env.getProvidedInterfaces().get(0),
- container.getRequiredInterfaces().get(0).getProvider());
+ assertSame(env.getProvidedInterfaces().get(0), container
+ .getRequiredInterfaces().get(0).getProvider());
assertNull(container.getRequiredInterfaces().get(1).getProvider());
- assertSame(env.getProvidedInterfaces().get(0),
- application.getRequiredInterfaces().get(0).getProvider());
+ assertSame(env.getProvidedInterfaces().get(0), application
+ .getRequiredInterfaces().get(0).getProvider());
assertNull(application.getRequiredInterfaces().get(1).getProvider());
}
- /**
- * DOCUMENT ME!
- */
public void testOptionalRequiredInterfaceProvidedMandatoryInternal() {
Application application = new Application();
- Container container = new Container("top",
- new Component[] { application }, new ProvidedInterface[0],
- Application.required(true));
- Environment env = new Environment();
- container.getRequiredInterfaces().get(0)
- .setProvider(env.getProvidedInterfaces().get(0));
- container.getRequiredInterfaces().get(1)
- .setProvider(env.getProvidedInterfaces().get(1));
+ Container container = new Container("top",
+ new Component[] { application }, new ProvidedInterface[0],
+ Application.required(true));
+ Environment env = new Environment();
+ container.getRequiredInterfaces().get(0).setProvider(
+ env.getProvidedInterfaces().get(0));
+ container.getRequiredInterfaces().get(1).setProvider(
+ env.getProvidedInterfaces().get(1));
try {
container.start();
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testSealed() {
final Container container = new Container("xx");
assertFalse(container.isSealed());
assertTrue(container.isSealed());
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.addComponent(new Application());
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.addComponent(new Application());
+ }
+ }, SystemAssemblyException.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectRequiredProvided("x", "y", "a", "b");
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectRequiredProvided("x", "y", "a", "b");
+ }
+ }, SystemAssemblyException.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalRequired("x", "y", "a");
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectExternalRequired("x", "y", "a");
+ }
+ }, SystemAssemblyException.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalProvided("x", "y", "z");
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectExternalProvided("x", "y", "z");
+ }
+ }, SystemAssemblyException.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.addProvidedInterface(new DefaultProvidedInterface(
- "xx", String.class));
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.addProvidedInterface(new DefaultProvidedInterface(
+ "xx", String.class));
+ }
+ }, SystemAssemblyException.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.addRequiredInterface(new DefaultRequiredInterface(
- "xx", String.class));
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.addRequiredInterface(new DefaultRequiredInterface(
+ "xx", String.class));
+ }
+ }, SystemAssemblyException.class);
}
- /**
- * DOCUMENT ME!
- */
public void testRestriction() {
- Environment env1 = new Environment("env1");
- Environment env2 = new Environment("env2");
- Application app = new Application("app");
- Container container = new Container("top").addComponent(env1)
+ Environment env1 = new Environment("env1");
+ Environment env2 = new Environment("env2");
+ Application app = new Application("app");
+ Container container = new Container("top").addComponent(env1)
.addComponent(env2).addComponent(app);
container.connectRequiredProvided("app", null, "env1", null);
container.start();
assertFalse(env2.getInteger().equals(app.getInteger()));
}
- /**
- * DOCUMENT ME!
- */
public void testRestrictionWithFromAndToInterfaceName() {
- Environment env1 = new Environment("env1");
- Environment env2 = new Environment("env2");
- Application app = new Application("app");
- Container container = new Container("top").addComponent(env1)
+ Environment env1 = new Environment("env1");
+ Environment env2 = new Environment("env2");
+ Application app = new Application("app");
+ Container container = new Container("top").addComponent(env1)
.addComponent(env2).addComponent(app);
- container.connectRequiredProvided("app",
- app.getRequiredInterfaces().get(0).getName(), "env1",
- env1.getProvidedInterfaces().get(0).getName());
- container.connectRequiredProvided("app",
- app.getRequiredInterfaces().get(1).getName(), "env2",
- env2.getProvidedInterfaces().get(1).getName());
+ container.connectRequiredProvided("app", app.getRequiredInterfaces()
+ .get(0).getName(), "env1", env1.getProvidedInterfaces().get(0)
+ .getName());
+ container.connectRequiredProvided("app", app.getRequiredInterfaces()
+ .get(1).getName(), "env2", env2.getProvidedInterfaces().get(1)
+ .getName());
container.start();
assertEquals(env1.getString(), app.getString());
assertEquals(env2.getInteger(), app.getInteger());
assertFalse(env1.getInteger().equals(app.getInteger()));
}
- /**
- * DOCUMENT ME!
- */
public void testRestrictionWrongComponentNames() {
- Environment env1 = new Environment("env1");
- Environment env2 = new Environment("env2");
- Application app = new Application("app");
+ Environment env1 = new Environment("env1");
+ Environment env2 = new Environment("env2");
+ Application app = new Application("app");
final Container container = new Container("top").addComponent(env1)
.addComponent(env2).addComponent(app);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectRequiredProvided("app2", null, "env1", null);
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectRequiredProvided("app2", null, "env1", null);
+ }
+ }, SystemAssemblyException.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectRequiredProvided("app", null, "env3", null);
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectRequiredProvided("app", null, "env3", null);
+ }
+ }, SystemAssemblyException.class);
}
- /**
- * DOCUMENT ME!
- */
public void testRestrictionWrongInterfaceNames() {
- final Environment env1 = new Environment("env1");
- Environment env2 = new Environment("env2");
- final Application app = new Application("app");
- final Container container = new Container("top").addComponent(env1)
+ final Environment env1 = new Environment("env1");
+ Environment env2 = new Environment("env2");
+ final Application app = new Application("app");
+ final Container container = new Container("top").addComponent(env1)
.addComponent(env2).addComponent(app);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectRequiredProvided("app",
- app.getRequiredInterfaces().get(0).getName() + "xxx",
- "env1", null);
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectRequiredProvided("app", app
+ .getRequiredInterfaces().get(0).getName() +
+ "xxx", "env1", null);
+ }
+ }, SystemAssemblyException.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectRequiredProvided("app", null, "env1",
- env1.getProvidedInterfaces().get(0).getName() + "yyy");
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectRequiredProvided("app", null, "env1", env1
+ .getProvidedInterfaces().get(0).getName() +
+ "yyy");
+ }
+ }, SystemAssemblyException.class);
}
- /**
- * DOCUMENT ME!
- */
public void testProvidedInDifferentScopes() {
// Scoping problem occurred. Externally and internally provided
// components clashed
// because unique id generation in the scope was wrong.
- StringComponent str = new StringComponent("string");
- Application app = new Application("app");
- Container container = new Container("top").addComponent(str)
+ StringComponent str = new StringComponent("string");
+ Application app = new Application("app");
+ Container container = new Container("top").addComponent(str)
.addComponent(app);
container.addRequiredInterface(new DefaultRequiredInterface("integer",
- Integer.class));
+ Integer.class));
ProvidedInterface provided = new DefaultProvidedInterface("hallo",
- Integer.class);
+ Integer.class);
container.getRequiredInterfaces().get(0).setProvider(provided);
Scope external = new DefaultScope(new ProvidedInterface[0]);
Scope scope = container.start(external);
}
- /**
- * DOCUMENT ME!
- */
public void testProvidedInterfaces() {
- Environment env = new Environment(tracker);
- Container envcontainer = new Container("0").addComponent(env)
- .addProvidedInterface(new DefaultProvidedInterface("string",
- String.class))
- .addProvidedInterface(new DefaultProvidedInterface("integer",
- Integer.class));
- Scope scope = envcontainer.start();
+ Environment env = new Environment(tracker);
+ Container envcontainer = new Container("0").addComponent(env)
+ .addProvidedInterface(
+ new DefaultProvidedInterface("string", String.class))
+ .addProvidedInterface(
+ new DefaultProvidedInterface("integer", Integer.class));
+ Scope scope = envcontainer.start();
AssertionUtils.assertEquals(new String[] { "start.environment" },
tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
envcontainer.stop(scope);
}
- /**
- * DOCUMENT ME!
- */
public void testCoupleTwoContainers() {
- 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);
- Container appcontainer = new Container("1").addComponent(app)
- .addRequiredInterface(new DefaultRequiredInterface("string",
- String.class))
- .addRequiredInterface(new DefaultRequiredInterface("integer",
- Integer.class));
-
- Container top = new Container("top");
+ 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);
+ Container appcontainer = new Container("1").addComponent(app)
+ .addRequiredInterface(
+ new DefaultRequiredInterface("string", String.class))
+ .addRequiredInterface(
+ new DefaultRequiredInterface("integer", Integer.class));
+
+ Container top = new Container("top");
top.addComponent(envcontainer).addComponent(appcontainer);
top.start();
- AssertionUtils.assertEquals(new String[] {
- "start.environment", "start.application"
- }, tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ AssertionUtils.assertEquals(new String[] { "start.environment",
+ "start.application" }, tracker.getEvents(Thread.currentThread())
+ .toArray(new String[0]));
}
- /**
- * DOCUMENT ME!
- */
public void testNonUniqueRequiredInterface() {
final Container container = new Container("top");
container.addRequiredInterface(new DefaultRequiredInterface("i",
- Integer.class));
+ Integer.class));
container.addRequiredInterface(new DefaultRequiredInterface("x",
- String.class));
+ String.class));
container.addRequiredInterface(new DefaultRequiredInterface("y",
- String.class));
+ String.class));
Application app = new Application("1");
container.addComponent(app);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.start();
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.start();
+ }
+ }, SystemAssemblyException.class);
- container.connectExternalRequired("1",
- app.getRequiredInterfaces().get(0).getName(), "y");
+ container.connectExternalRequired("1", app.getRequiredInterfaces().get(
+ 0).getName(), "y");
- ProvidedInterface i = new DefaultProvidedInterface("i",
- Integer.class);
- ProvidedInterface x = new DefaultProvidedInterface("x",
- String.class);
- ProvidedInterface y = new DefaultProvidedInterface("y",
- String.class);
+ ProvidedInterface i = new DefaultProvidedInterface("i", Integer.class);
+ ProvidedInterface x = new DefaultProvidedInterface("x", String.class);
+ ProvidedInterface y = new DefaultProvidedInterface("y", String.class);
- Scope externalScope = new DefaultScope(new ProvidedInterface[0]);
+ Scope externalScope = new DefaultScope(new ProvidedInterface[0]);
externalScope.publishInterface(i, 100);
externalScope.publishInterface(x, "x-value");
assertEquals("y-value", app.getString());
}
- /**
- * DOCUMENT ME!
- */
public void testNonUniqueRequiredInterfaceWrongNames() {
final Container container = new Container("top");
container.addRequiredInterface(new DefaultRequiredInterface("i",
- Integer.class));
+ Integer.class));
container.addRequiredInterface(new DefaultRequiredInterface("x",
- String.class));
+ String.class));
container.addRequiredInterface(new DefaultRequiredInterface("y",
- String.class));
+ String.class));
final Application app = new Application("1");
container.addComponent(app);
// wrong component name.
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalRequired("2", "x", "y");
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectExternalRequired("2", "x", "y");
+ }
+ }, SystemAssemblyException.class);
// Wrong interface name of component.
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalRequired("1",
- app.getRequiredInterfaces().get(0).getName() + "xxx",
- "y");
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectExternalRequired("1", app
+ .getRequiredInterfaces().get(0).getName() +
+ "xxx", "y");
+ }
+ }, SystemAssemblyException.class);
// Wrong external interface name of container
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalRequired("1",
- app.getRequiredInterfaces().get(0).getName(), "z");
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectExternalRequired("1", app
+ .getRequiredInterfaces().get(0).getName(), "z");
+ }
+ }, SystemAssemblyException.class);
}
- /**
- * DOCUMENT ME!
- */
public void testNonUniqueProvidedInterface() {
- final Container container = new Container("top").addProvidedInterface(new DefaultProvidedInterface(
- "external", String.class));
- Environment env1 = new Environment("env1");
- Environment env2 = new Environment("env2");
+ final Container container = new Container("top")
+ .addProvidedInterface(new DefaultProvidedInterface("external",
+ String.class));
+ Environment env1 = new Environment("env1");
+ Environment env2 = new Environment("env2");
container.addComponent(env1);
container.addComponent(env2);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.start();
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.start();
+ }
+ }, SystemAssemblyException.class);
// now choose env2
container.connectExternalProvided(container.getProvidedInterfaces()
- .get(0).getName(), env2.getName(),
- env2.getProvidedInterfaces().get(0).getName());
+ .get(0).getName(), env2.getName(), env2.getProvidedInterfaces()
+ .get(0).getName());
Scope scope = container.start();
// check the value of the provided interface of the container
- String value = scope.getInterfaceImplementation(container.getProvidedInterfaces()
- .get(0), String.class);
+ String value = scope.getInterfaceImplementation(container
+ .getProvidedInterfaces().get(0), String.class);
assertNotNull(value);
assertEquals(value, env2.getString());
assertFalse(value.equals(env1.getString()));
}
- /**
- * DOCUMENT ME!
- */
public void testNonUniqueProvidedInterfaceWrongNames() {
- final Container container = new Container("top").addProvidedInterface(new DefaultProvidedInterface(
- "external", String.class));
- final Environment env1 = new Environment("env1");
- final Environment env2 = new Environment("env2");
+ final Container container = new Container("top")
+ .addProvidedInterface(new DefaultProvidedInterface("external",
+ String.class));
+ final Environment env1 = new Environment("env1");
+ final Environment env2 = new Environment("env2");
container.addComponent(env1);
container.addComponent(env2);
// Wrong external provided interface name
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalProvided(container.getProvidedInterfaces()
- .get(0).getName() + "xx", "env1",
- env1.getProvidedInterfaces().get(0).getName());
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container
+ .connectExternalProvided(container.getProvidedInterfaces()
+ .get(0).getName() +
+ "xx", "env1", env1.getProvidedInterfaces().get(0)
+ .getName());
+ }
+ }, SystemAssemblyException.class);
// Wrong provided interface name.
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalProvided(container.getProvidedInterfaces()
- .get(0).getName(), "env1",
- env1.getProvidedInterfaces().get(0).getName() + "xx");
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectExternalProvided(container
+ .getProvidedInterfaces().get(0).getName(), "env1", env1
+ .getProvidedInterfaces().get(0).getName() +
+ "xx");
+ }
+ }, SystemAssemblyException.class);
// Wrong provided component
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalProvided(container.getProvidedInterfaces()
- .get(0).getName(), "env3",
- env1.getProvidedInterfaces().get(0).getName());
- }
- }, SystemAssemblyException.class);
+ @Override
+ public void run() throws Exception {
+ container.connectExternalProvided(container
+ .getProvidedInterfaces().get(0).getName(), "env3", env1
+ .getProvidedInterfaces().get(0).getName());
+ }
+ }, SystemAssemblyException.class);
}
private static class MyMultiple implements Serializable, Runnable {
import junit.framework.TestCase;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class AbstractComponentTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
public void testNotAllInterfacesStarted() {
try {
Component<?> component = new AbstractComponent<Object>("xx",
- new ProvidedInterface[] {
- new DefaultProvidedInterface("xxx", String.class)
- }, new RequiredInterface[0]) {
- @Override
- protected Object doStart(Scope aScope) {
- // Empty, not starting service.
- return null;
- }
+ new ProvidedInterface[] { new DefaultProvidedInterface("xxx",
+ String.class) }, new RequiredInterface[0]) {
+ @Override
+ protected Object doStart(Scope aScope) {
+ // Empty, not starting service.
+ return null;
+ }
- @Override
- protected void doStop(Object aRuntime) {
- // Empty.
- }
- };
+ @Override
+ protected void doStop(Object aRuntime) {
+ // Empty.
+ }
+ };
- component.start(new DefaultScope(component.getProvidedInterfaces()));
+ component
+ .start(new DefaultScope(component.getProvidedInterfaces()));
} catch (SystemAssemblyException e) {
- //e.printStackTrace();
+ // e.printStackTrace();
return;
}
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testUnexpectedServicesStarted() {
try {
Component<?> component = new AbstractComponent<Object>("xx",
- new ProvidedInterface[0], new RequiredInterface[0]) {
- @Override
- protected Object doStart(Scope aScope) {
- addInterface(new DefaultProvidedInterface("x",
- Integer.class), 100, aScope);
+ new ProvidedInterface[0], new RequiredInterface[0]) {
+ @Override
+ protected Object doStart(Scope aScope) {
+ addInterface(new DefaultProvidedInterface("x",
+ Integer.class), 100, aScope);
- return null;
- }
+ return null;
+ }
- @Override
- protected void doStop(Object aRuntime) {
- // Empty.
- }
- };
+ @Override
+ protected void doStop(Object aRuntime) {
+ // Empty.
+ }
+ };
- component.start(new DefaultScope(component.getProvidedInterfaces()));
+ component
+ .start(new DefaultScope(component.getProvidedInterfaces()));
} catch (SystemAssemblyException e) {
- //e.printStackTrace();
+ // e.printStackTrace();
return;
}
import java.io.Serializable;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class DefaultInterfaceDescriptorTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
public void testOneRequiredOneProvidedMatch() {
ProvidedInterface provided = new DefaultProvidedInterface("name",
- String.class);
+ String.class);
RequiredInterface required = new DefaultRequiredInterface("name",
- String.class);
+ String.class);
assertTrue(required.implementedBy(provided));
}
- /**
- * DOCUMENT ME!
- */
public void testOneRequiredOneProvidedMatchSubClass() {
ProvidedInterface provided = new DefaultProvidedInterface("name",
- Integer.class);
+ Integer.class);
RequiredInterface required = new DefaultRequiredInterface("name",
- Number.class);
+ Number.class);
assertTrue(required.implementedBy(provided));
}
- /**
- * DOCUMENT ME!
- */
public void testOneRequiredOneProvidedNoMatch() {
ProvidedInterface provided = new DefaultProvidedInterface("name",
- String.class);
+ String.class);
RequiredInterface required = new DefaultRequiredInterface("name",
- Number.class);
+ Number.class);
assertFalse(required.implementedBy(provided));
}
- /**
- * DOCUMENT ME!
- */
public void testOneRequiredMultipleProvidedMatch() {
ProvidedInterface provided = new DefaultProvidedInterface("name",
- new Class[] { String.class, Integer.class });
+ new Class[] { String.class, Integer.class });
RequiredInterface required = new DefaultRequiredInterface("name",
- String.class);
+ String.class);
assertTrue(required.implementedBy(provided));
}
- /**
- * DOCUMENT ME!
- */
public void testMultipleRequiredOneProvidedMatch() {
ProvidedInterface provided = new DefaultProvidedInterface("name",
- MyMultiple.class);
+ MyMultiple.class);
RequiredInterface required = new DefaultRequiredInterface("name",
- new Class[] { Runnable.class, Serializable.class });
+ new Class[] { Runnable.class, Serializable.class });
assertTrue(required.implementedBy(provided));
}
- /**
- * DOCUMENT ME!
- */
public void testMultipleRequiredOneProvidedNoMatch() {
ProvidedInterface provided = new DefaultProvidedInterface("name",
- MyMultiple.class);
+ MyMultiple.class);
RequiredInterface required = new DefaultRequiredInterface("name",
- new Class[] { String.class, Runnable.class });
+ new Class[] { String.class, Runnable.class });
assertFalse(required.implementedBy(provided));
}
- /**
- * DOCUMENT ME!
- */
public void testMultipleRequiredMultipleProvidedMatch() {
ProvidedInterface provided = new DefaultProvidedInterface("name",
- new Class[] { Runnable.class, Serializable.class, String.class });
+ new Class[] { Runnable.class, Serializable.class, String.class });
RequiredInterface required = new DefaultRequiredInterface("name",
- new Class[] { Runnable.class, Serializable.class });
+ new Class[] { Runnable.class, Serializable.class });
assertTrue(required.implementedBy(provided));
}
- /**
- * DOCUMENT ME!
- */
public void testPrimitiveAndWrapperType() {
- RequiredInterface req1 = new DefaultRequiredInterface("req1", int.class);
- RequiredInterface req2 = new DefaultRequiredInterface("req1",
- Integer.class);
+ RequiredInterface req1 = new DefaultRequiredInterface("req1", int.class);
+ RequiredInterface req2 = new DefaultRequiredInterface("req1",
+ Integer.class);
ProvidedInterface prov1 = new DefaultProvidedInterface("prov1",
- int.class);
+ int.class);
ProvidedInterface prov2 = new DefaultProvidedInterface("prov2",
- Integer.class);
+ Integer.class);
assertTrue(req1.implementedBy(prov1));
assertTrue(req2.implementedBy(prov1));
assertTrue(req1.implementedBy(prov2));
private static class MyMultiple implements Runnable, Serializable {
@Override
public void run() {
- // Empty
+ // Empty
}
}
}
import junit.framework.TestCase;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class DefaultRequiredInterfaceTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
public void testEquals() {
- assertFalse(new DefaultRequiredInterface("a", String.class).equals(
- new DefaultRequiredInterface("a", String.class)));
+ assertFalse(new DefaultRequiredInterface("a", String.class)
+ .equals(new DefaultRequiredInterface("a", String.class)));
}
}
import junit.framework.TestCase;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class DefaultScopeTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
public void testLookup() {
ProvidedInterface provider = new DefaultProvidedInterface("x",
- Integer.class);
- Scope scope = new DefaultScope(new ProvidedInterface[0]);
+ Integer.class);
+ Scope scope = new DefaultScope(new ProvidedInterface[0]);
scope.publishInterface(provider, 100);
- assertEquals(100,
- scope.getInterfaceImplementation(provider, Integer.class).intValue());
+ assertEquals(100, scope.getInterfaceImplementation(provider,
+ Integer.class).intValue());
}
- /**
- * DOCUMENT ME!
- */
public void testNestedLookup() {
ProvidedInterface provider1 = new DefaultProvidedInterface("x",
- Integer.class);
- Scope parent = new DefaultScope(new ProvidedInterface[0]);
+ Integer.class);
+ Scope parent = new DefaultScope(new ProvidedInterface[0]);
parent.publishInterface(provider1, 100);
ProvidedInterface provider2 = new DefaultProvidedInterface("y",
- String.class);
- Scope child = new DefaultScope(new ProvidedInterface[0],
- parent);
+ String.class);
+ Scope child = new DefaultScope(new ProvidedInterface[0], parent);
child.publishInterface(provider2, "hallo");
assertFalse(provider1.equals(provider2));
- assertEquals(100,
- child.getInterfaceImplementation(provider1, Integer.class).intValue());
- assertEquals("hallo",
- child.getInterfaceImplementation(provider2, String.class));
+ assertEquals(100, child.getInterfaceImplementation(provider1,
+ Integer.class).intValue());
+ assertEquals("hallo", child.getInterfaceImplementation(provider2,
+ String.class));
}
}
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class Environment extends AbstractComponent<Object> {
- /**
- * DOCUMENT ME!
- */
private static int COUNT = 0;
- /**
- * DOCUMENT ME!
- */
private EventTracker<String> tracker;
- /**
- * DOCUMENT ME!
- */
private double random;
- /**
- * DOCUMENT ME!
- */
private int integer;
/**
/**
* Creates a new Environment object.
- *
- * @param aName DOCUMENT ME!
+ *
*/
public Environment(String aName) {
this(aName, "");
/**
* Creates a new Environment object.
- *
- * @param aName DOCUMENT ME!
- * @param aPrefix DOCUMENT ME!
+ *
*/
public Environment(String aName, String aPrefix) {
super(aName, provided(aPrefix), new RequiredInterface[0]);
- random = Math.random();
- integer = COUNT++;
+ random = Math.random();
+ integer = COUNT++;
}
/**
* Creates a new Environment object.
- *
- * @param aTracker DOCUMENT ME!
+ *
*/
public Environment(EventTracker aTracker) {
this();
tracker = aTracker;
}
- /**
- * DOCUMENT ME!
- *
- * @param aPrefix DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static final ProvidedInterface[] provided(String aPrefix) {
return new ProvidedInterface[] {
new DefaultProvidedInterface(aPrefix + "datasource", String.class),
- new DefaultProvidedInterface(aPrefix + "integer", Integer.class)
- };
+ new DefaultProvidedInterface(aPrefix + "integer", Integer.class) };
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Integer getInteger() {
return integer;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String getString() {
return getName() + ".hello";
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Object doStart(Scope aScope) {
addInterface(getProvidedInterfaces().get(0), getString(), aScope);
return random;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
protected void doStop(Object aRuntime) {
track("stop." + getName());
if (random != (Double) aRuntime) {
- throw new IllegalArgumentException("Wrong runtime: expected "
- + random + " but got " + aRuntime);
+ throw new IllegalArgumentException("Wrong runtime: expected " +
+ random + " but got " + aRuntime);
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aString DOCUMENT ME!
- */
private void track(String aString) {
if (tracker == null) {
return;
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class IntegerComponent extends AbstractComponent<Object> {
- /**
- * DOCUMENT ME!
- */
private EventTracker<String> tracker;
- /**
- * DOCUMENT ME!
- */
private double random;
/**
/**
* Creates a new IntegerComponent object.
- *
- * @param aName DOCUMENT ME!
+ *
*/
public IntegerComponent(String aName) {
this(aName, "");
/**
* Creates a new IntegerComponent object.
- *
- * @param aName DOCUMENT ME!
- * @param aPrefix DOCUMENT ME!
+ *
*/
public IntegerComponent(String aName, String aPrefix) {
super(aName, provided(aPrefix), new RequiredInterface[0]);
/**
* Creates a new IntegerComponent object.
- *
- * @param aTracker DOCUMENT ME!
+ *
*/
public IntegerComponent(EventTracker aTracker) {
this();
tracker = aTracker;
}
- /**
- * DOCUMENT ME!
- *
- * @param aPrefix DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static final ProvidedInterface[] provided(String aPrefix) {
- return new ProvidedInterface[] {
- new DefaultProvidedInterface(aPrefix + "integer", Integer.class)
- };
+ return new ProvidedInterface[] { new DefaultProvidedInterface(aPrefix +
+ "integer", Integer.class) };
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Integer getInteger() {
return 2;
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Object doStart(Scope aScope) {
addInterface(getProvidedInterfaces().get(1), getInteger(), aScope);
return random;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
protected void doStop(Object aRuntime) {
track("stop." + getName());
if (random != (Double) aRuntime) {
- throw new IllegalArgumentException("Wrong runtime: expected "
- + random + " but got " + aRuntime);
+ throw new IllegalArgumentException("Wrong runtime: expected " +
+ random + " but got " + aRuntime);
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aString DOCUMENT ME!
- */
private void track(String aString) {
if (tracker == null) {
return;
import java.util.Comparator;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
-public class RequiredInterfaceComparator implements Comparator<RequiredInterface> {
- /**
- * DOCUMENT ME!
- *
- * @param aO1 DOCUMENT ME!
- * @param aO2 DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
+ */
+public class RequiredInterfaceComparator implements
+ Comparator<RequiredInterface> {
@Override
public int compare(RequiredInterface aO1, RequiredInterface aO2) {
return aO1.getName().compareTo(aO2.getName());
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class StringComponent extends AbstractComponent<Object> {
- /**
- * DOCUMENT ME!
- */
private EventTracker<String> tracker;
- /**
- * DOCUMENT ME!
- */
private double random;
/**
/**
* Creates a new StringComponent object.
- *
- * @param aName DOCUMENT ME!
+ *
*/
public StringComponent(String aName) {
this(aName, "");
/**
* Creates a new StringComponent object.
- *
- * @param aName DOCUMENT ME!
- * @param aPrefix DOCUMENT ME!
+ *
*/
public StringComponent(String aName, String aPrefix) {
super(aName, provided(aPrefix), new RequiredInterface[0]);
/**
* Creates a new StringComponent object.
- *
- * @param aTracker DOCUMENT ME!
+ *
*/
public StringComponent(EventTracker aTracker) {
this();
tracker = aTracker;
}
- /**
- * DOCUMENT ME!
- *
- * @param aPrefix DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static final ProvidedInterface[] provided(String aPrefix) {
- return new ProvidedInterface[] {
- new DefaultProvidedInterface(aPrefix + "datasource", String.class)
- };
+ return new ProvidedInterface[] { new DefaultProvidedInterface(aPrefix +
+ "datasource", String.class) };
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Integer getInteger() {
return 2;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String getString() {
return getName() + ".hello";
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Object doStart(Scope aScope) {
addInterface(getProvidedInterfaces().get(0), getString(), aScope);
return random;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
protected void doStop(Object aRuntime) {
track("stop." + getName());
if (random != (Double) aRuntime) {
- throw new IllegalArgumentException("Wrong runtime: expected "
- + random + " but got " + aRuntime);
+ throw new IllegalArgumentException("Wrong runtime: expected " +
+ random + " but got " + aRuntime);
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aString DOCUMENT ME!
- */
private void track(String aString) {
if (tracker == null) {
return;
import org.wamblee.system.graph.component.ProvidedInterfaceNode;
import org.wamblee.system.graph.component.RequiredInterfaceNode;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class CompositeEdgeFilterTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
private Application app = new Application();
- /**
- * DOCUMENT ME!
- */
private Environment env = new Environment();
- /**
- * DOCUMENT ME!
- *
- * @param aClient DOCUMENT ME!
- * @param aRequired DOCUMENT ME!
- * @param aServer DOCUMENT ME!
- * @param aProvided DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private Edge createEdge(Component aClient, RequiredInterface aRequired,
Component aServer, ProvidedInterface aProvided) {
Node from = new RequiredInterfaceNode(aClient, aRequired);
- Node to = new ProvidedInterfaceNode(aServer, aProvided);
+ Node to = new ProvidedInterfaceNode(aServer, aProvided);
return new DefaultEdge(from, to);
}
- /**
- * DOCUMENT ME!
- */
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))));
}
- /**
- * DOCUMENT ME!
- *
- * @param base DOCUMENT ME!
- * @param aResult DOCUMENT ME!
- */
private void configureRestriction(EdgeFilter base, boolean aResult) {
stub(base.isViolated((Edge) anyObject())).toReturn(aResult);
}
- /**
- * DOCUMENT ME!
- */
public void testOneRestriction() {
- EdgeFilter base = mock(EdgeFilter.class);
+ EdgeFilter base = mock(EdgeFilter.class);
CompositeEdgeFilter composite = new CompositeEdgeFilter();
composite.add(base);
- // First let the base return false and verify the result.
+ // First let the base return false and verify the result.
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))));
}
- /**
- * DOCUMENT ME!
- */
public void testTwoRestrictions() {
- EdgeFilter base1 = mock(EdgeFilter.class);
+ EdgeFilter base1 = mock(EdgeFilter.class);
CompositeEdgeFilter composite = new CompositeEdgeFilter();
composite.add(base1);
EdgeFilter base2 = mock(EdgeFilter.class);
composite.add(base2);
- // 1. base1 not violated and base 2 not violated -> not violated.
+ // 1. base1 not violated and base 2 not violated -> not violated.
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.
+ // 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))));
}
}
import java.util.Arrays;
import java.util.List;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class GraphTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
public void testNodeMgt() {
final Graph graph = new Graph();
assertTrue(graph.getNodes().isEmpty());
assertTrue(graph.removeNode(x));
assertTrue(graph.getNodes().isEmpty());
- // Empty node set.
+ // Empty node set.
assertFalse(graph.removeNode(x));
Node y = new DefaultNode("y");
// duplicate node
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- graph.addNode(new DefaultNode("x"));
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ graph.addNode(new DefaultNode("x"));
+ }
+ }, IllegalArgumentException.class);
}
- /**
- * DOCUMENT ME!
- */
public void testEdgeMgt() {
final Graph graph = new Graph();
- final Node x = new DefaultNode("x");
- final Node y = new DefaultNode("y");
+ final Node x = new DefaultNode("x");
+ final Node y = new DefaultNode("y");
graph.addNode(x);
graph.addNode(y);
// duplicate edge.
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- graph.addEdge(e);
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ graph.addEdge(e);
+ }
+ }, IllegalArgumentException.class);
// Remove node when edge is still present
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- graph.removeNode(x);
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ graph.removeNode(x);
+ }
+ }, IllegalArgumentException.class);
Node a = new DefaultNode("a");
graph.addNode(a);
- graph.addEdges(Arrays.asList(
- new Edge[] { new DefaultEdge(x, a), new DefaultEdge(y, a) }));
+ graph.addEdges(Arrays.asList(new Edge[] { new DefaultEdge(x, a),
+ new DefaultEdge(y, a) }));
assertEquals(3, graph.getEdges().size());
}
- /**
- * DOCUMENT ME!
- */
public void testExtend() {
Graph graph = new Graph();
graph.addNode(new MyNode("x", new String[] { "a", "b" }));
assertEquals(12, edges.size()); // 2 outgoing and 2 incoming nodes.
}
- /**
- * DOCUMENT ME!
- */
public void testApplyFilter() {
Graph graph = new Graph();
graph.addNode(new DefaultNode("x"));
graph.addNode(new DefaultNode("y"));
graph.addNode(new DefaultNode("z"));
- graph.addEdge(new DefaultEdge(graph.findNode("x"), graph.findNode("y")));
- graph.addEdge(new DefaultEdge(graph.findNode("y"), graph.findNode("z")));
- graph.addEdge(new DefaultEdge(graph.findNode("z"), graph.findNode("x")));
+ graph
+ .addEdge(new DefaultEdge(graph.findNode("x"), graph.findNode("y")));
+ graph
+ .addEdge(new DefaultEdge(graph.findNode("y"), graph.findNode("z")));
+ graph
+ .addEdge(new DefaultEdge(graph.findNode("z"), graph.findNode("x")));
assertEquals(3, graph.getEdges().size());
graph.applyFilter(new EdgeFilter() {
- @Override
- public boolean isViolated(Edge aEdge) {
- if (aEdge.getFrom().getName().equals("x")) {
- return false;
- }
-
- return true;
+ @Override
+ public boolean isViolated(Edge aEdge) {
+ if (aEdge.getFrom().getName().equals("x")) {
+ return false;
}
- });
+
+ return true;
+ }
+ });
assertEquals(1, graph.getEdges().size());
assertEquals("x", graph.getEdges().get(0).getFrom().getName());
}
- /**
- * DOCUMENT ME!
- */
public void testFindIncomingOutgoing() {
Graph graph = new Graph();
- Node x = new DefaultNode("x");
- Node y = new DefaultNode("y");
+ Node x = new DefaultNode("x");
+ Node y = new DefaultNode("y");
graph.addNode(x);
graph.addNode(y);
assertTrue(outgoing.isEmpty());
}
- /**
- * DOCUMENT ME!
- */
public void testAccept() {
Graph graph = new Graph();
- Node x = new DefaultNode("x");
- Node y = new DefaultNode("y");
- Edge e = new DefaultEdge(x, y);
+ Node x = new DefaultNode("x");
+ Node y = new DefaultNode("y");
+ Edge e = new DefaultEdge(x, y);
graph.addNode(x);
graph.addNode(y);
graph.addEdge(e);
import java.util.ArrayList;
import java.util.List;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class MyEdgeFactory implements EdgeFactory<MyNode> {
/**
* Creates a new MyEdgeFactory object.
// Empty.
}
- /**
- * DOCUMENT ME!
- *
- * @param aFrom DOCUMENT ME!
- * @param aTo DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public List<Edge> create(MyNode aFrom, MyNode aTo) {
List<Edge> result = new ArrayList<Edge>();
package org.wamblee.system.graph;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class MyNode extends DefaultNode {
- /**
- * DOCUMENT ME!
- */
private String[] ports;
/**
* Creates a new MyNode object.
- *
- * @param aName DOCUMENT ME!
- * @param aPorts DOCUMENT ME!
+ *
*/
public MyNode(String aName, String[] aPorts) {
super(aName);
ports = aPorts;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String[] getPorts() {
return ports;
}
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.EdgeFilter;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class ConnectExternalProvidedProvidedEdgeFilterTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
private Container container;
- /**
- * DOCUMENT ME!
- */
private Component<Object> internal;
- /**
- * DOCUMENT ME!
- */
private String externalInterfaceName;
- /**
- * DOCUMENT ME!
- */
private String internalComponentName;
- /**
- * DOCUMENT ME!
- */
private String internalInterfaceName;
- /**
- * DOCUMENT ME!
- */
private Edge edge;
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
- container = new Container("container")
+ container = new Container("container")
.addProvidedInterface(new DefaultProvidedInterface("string",
- String.class));
- internal = new Environment("env1");
+ String.class));
+ internal = new Environment("env1");
- externalInterfaceName = container.getProvidedInterfaces().get(0)
+ externalInterfaceName = container.getProvidedInterfaces().get(0)
.getName();
- internalComponentName = internal.getName();
- internalInterfaceName = internal.getProvidedInterfaces().get(0)
+ internalComponentName = internal.getName();
+ internalInterfaceName = internal.getProvidedInterfaces().get(0)
.getName();
- edge = new DefaultEdge(new ExternalProvidedInterfaceNode(
- container, container.getProvidedInterfaces().get(0)),
- new ProvidedInterfaceNode(internal,
- internal.getProvidedInterfaces().get(0)));
+ edge = new DefaultEdge(new ExternalProvidedInterfaceNode(container,
+ container.getProvidedInterfaces().get(0)),
+ new ProvidedInterfaceNode(internal, internal
+ .getProvidedInterfaces().get(0)));
}
- /**
- * DOCUMENT ME!
- */
public void testWrongExternal() {
- EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName
- + "x", internalComponentName, internalInterfaceName);
+ EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
+ externalInterfaceName + "x", internalComponentName,
+ internalInterfaceName);
assertFalse(filter.isViolated(edge));
}
- /**
- * DOCUMENT ME!
- */
public void testRightExternalWrongComponent() {
- EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName,
- internalComponentName + "x", internalInterfaceName);
+ EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
+ externalInterfaceName, internalComponentName + "x",
+ internalInterfaceName);
assertTrue(filter.isViolated(edge));
}
- /**
- * DOCUMENT ME!
- */
public void testRightExternalWrongInternal() {
- EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName,
- internalComponentName, internalInterfaceName + "x");
+ EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
+ externalInterfaceName, internalComponentName,
+ internalInterfaceName + "x");
assertTrue(filter.isViolated(edge));
}
- /**
- * DOCUMENT ME!
- */
public void testEverythingRight() {
- EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName,
- internalComponentName, internalInterfaceName);
+ EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
+ externalInterfaceName, internalComponentName, internalInterfaceName);
assertFalse(filter.isViolated(edge));
}
- /**
- * DOCUMENT ME!
- */
public void testWrongEdgeType() {
- EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName,
- internalComponentName, internalInterfaceName);
- DefaultEdge edge = new DefaultEdge(new DefaultNode("x"),
- new DefaultNode("y"));
+ EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
+ externalInterfaceName, internalComponentName, internalInterfaceName);
+ DefaultEdge edge = new DefaultEdge(new DefaultNode("x"),
+ new DefaultNode("y"));
assertFalse(filter.isViolated(edge));
}
}
import org.wamblee.system.graph.EdgeFilter;
import org.wamblee.system.graph.Node;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class ConnectRequiredExternallyRequiredEdgeFilterTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
private Component<?> comp;
- /**
- * DOCUMENT ME!
- */
private Container container;
- /**
- * DOCUMENT ME!
- */
private Edge edge;
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
- comp = new Application();
- container = new Container("container").addRequiredInterface(new DefaultRequiredInterface(
- "x", String.class));
+ comp = new Application();
+ container = new Container("container")
+ .addRequiredInterface(new DefaultRequiredInterface("x",
+ String.class));
- Node req = new RequiredInterfaceNode(comp,
- comp.getRequiredInterfaces().get(0));
- Node external = new ExternalRequiredInterfaceNode(container,
- container.getRequiredInterfaces().get(0));
- edge = new DefaultEdge(req, external);
+ Node req = new RequiredInterfaceNode(comp, comp.getRequiredInterfaces()
+ .get(0));
+ Node external = new ExternalRequiredInterfaceNode(container, container
+ .getRequiredInterfaces().get(0));
+ edge = new DefaultEdge(req, external);
}
- /**
- * DOCUMENT ME!
- */
public void testRightComponentRightInterface() {
- EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp
- .getName(), comp.getRequiredInterfaces().get(0).getName(),
- container.getRequiredInterfaces().get(0).getName());
+ EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
+ comp.getName(), comp.getRequiredInterfaces().get(0).getName(),
+ container.getRequiredInterfaces().get(0).getName());
assertFalse(filter.isViolated(edge));
}
- /**
- * DOCUMENT ME!
- */
public void testWrongInterface() {
- EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp
- .getName(),
- comp.getRequiredInterfaces().get(0).getName() + "xx",
- container.getRequiredInterfaces().get(0).getName());
+ EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
+ comp.getName(), comp.getRequiredInterfaces().get(0).getName() +
+ "xx", container.getRequiredInterfaces().get(0).getName());
assertFalse(filter.isViolated(edge));
}
- /**
- * DOCUMENT ME!
- */
public void testWrongComponent() {
- EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp
- .getName() + "xx",
- comp.getRequiredInterfaces().get(0).getName(),
- container.getRequiredInterfaces().get(0).getName());
+ EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
+ comp.getName() + "xx", comp.getRequiredInterfaces().get(0)
+ .getName(), container.getRequiredInterfaces().get(0).getName());
assertFalse(filter.isViolated(edge));
}
- /**
- * DOCUMENT ME!
- */
public void testWrongExternalInterface() {
- EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp
- .getName(), comp.getRequiredInterfaces().get(0).getName(),
- container.getRequiredInterfaces().get(0).getName() + "xx");
+ EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
+ comp.getName(), comp.getRequiredInterfaces().get(0).getName(),
+ container.getRequiredInterfaces().get(0).getName() + "xx");
assertTrue(filter.isViolated(edge));
}
- /**
- * DOCUMENT ME!
- */
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());
+ 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());
assertFalse(filter.isViolated(edge));
}
}
import java.util.Arrays;
import java.util.List;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
- */
+ */
public class ConnectRequiredProvidedEdgeFilterTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
private Application app1 = new Application("app1", "pf1.");
- /**
- * DOCUMENT ME!
- */
private Application app2 = new Application("app2", "pf2.");
- /**
- * DOCUMENT ME!
- */
private Environment env1 = new Environment("env1", "pf3.");
- /**
- * DOCUMENT ME!
- */
private Environment env2 = new Environment("env2", "pf4.");
- /**
- * DOCUMENT ME!
- *
- * @param aExpected DOCUMENT ME!
- * @param aRestriction DOCUMENT ME!
- */
private void compare(Boolean[] aExpected, EdgeFilter aRestriction) {
List<Boolean> result = new ArrayList<Boolean>();
- // order will be:
- // env1, app1
- // env1, app2
- // env2, app1
- // env2, app2
+ // order will be:
+ // env1, app1
+ // env1, app2
+ // env2, app1
+ // env2, 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(env,
- env.getProvidedInterfaces().get(0));
+ Node from = new RequiredInterfaceNode(app, app
+ .getRequiredInterfaces().get(0));
+ Node to = new ProvidedInterfaceNode(env, env
+ .getProvidedInterfaces().get(0));
Edge edge = new DefaultEdge(from, to);
result.add(aRestriction.isViolated(edge));
}
assertEquals(Arrays.asList(aExpected), result);
}
- /**
- * DOCUMENT ME!
- */
public void testNoRestriction() {
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null,
- null, null, null);
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(
+ null, null, null, null);
+ }
+ }, IllegalArgumentException.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null,
- null, "x", "y");
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(
+ null, null, "x", "y");
+ }
+ }, IllegalArgumentException.class);
}
- /**
- * DOCUMENT ME!
- */
public void testClientServer() {
EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app1",
- null, "env1", null);
+ null, "env1", null);
compare(new Boolean[] { false, false, true, false }, restriction);
}
- /**
- * DOCUMENT ME!
- */
public void testNoConnectionsAtAll() {
EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app1",
- null, null, null);
+ null, null, null);
compare(new Boolean[] { true, false, true, false }, restriction);
}
- /**
- * DOCUMENT ME!
- */
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");
+ "string", "env1", "datasource");
compare(new Boolean[] { false, false, false, true }, restriction);
}
}
import java.util.Properties;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class ConfiguredProperties extends Properties {
-/**
+ /**
* Creates a new ConfiguredProperties object.
- *
- * @param aProps DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
+ *
+ *
*/
public ConfiguredProperties(String aProps) throws IOException {
InputStream is = new ByteArrayInputStream(aProps.getBytes());
import java.util.Properties;
-
/**
- * Bean that provides postprocessing of the bean factory based on a given
- * set of properties.
- *
+ * Bean that provides postprocessing of the bean factory based on a given set of
+ * properties.
+ *
* @author Erik Brakkee
*/
class PropertySetter extends PropertyPlaceholderConfigurer {
-/**
- * Constructs the property setter.
- * @param aProps Properties.
- */
+ /**
+ * Constructs the property setter.
+ *
+ * @param aProps
+ * Properties.
+ */
public PropertySetter(Properties aProps) {
String propFile = createPropertyFile(aProps);
setLocation(new StringResource(propFile));
}
- /**
- * DOCUMENT ME!
- *
- * @param aProps DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public static String createPropertyFile(Properties aProps) {
StringBuffer buf = new StringBuffer();
import java.util.List;
-
/**
- * Bean which adds a service required by the spring component to the
- * application context so that other spring beans can use it.
- *
+ * Bean which adds a service required by the spring component to the application
+ * context so that other spring beans can use it.
+ *
* @author Erik Brakkee
*/
class RequiredServiceBean implements FactoryBean {
- /**
- * DOCUMENT ME!
- */
private RequiredInterface _required;
-/**
- * Constructs the bean.
- * @param aId Id of the bean in the service registry.
- */
+ /**
+ * Constructs the bean.
+ *
+ * @param aId
+ * Id of the bean in the service registry.
+ */
public RequiredServiceBean(String aId) {
List<RequiredInterface> required = SpringComponent.THIS.get()
.getRequiredInterfaces();
}
}
- throw new SystemAssemblyException("Cannot resolve required component '"
- + aId + "'");
+ throw new SystemAssemblyException(
+ "Cannot resolve required component '" + aId + "'");
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
public Object getObject() throws Exception {
- return SpringComponent.SCOPE.get()
- .getInterfaceImplementation(_required.getProvider(), Object.class);
+ return SpringComponent.SCOPE.get().getInterfaceImplementation(
+ _required.getProvider(), Object.class);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public Class getObjectType() {
return null;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean isSingleton() {
return true;
import java.util.Map;
import java.util.Properties;
-
/**
- * Represents a system configured based on spring. The spring config files
- * that are configured should not contain any PropertyPlaceholderConfigurer
- * objects.
- *
+ * Represents a system configured based on spring. The spring config files that
+ * are configured should not contain any PropertyPlaceholderConfigurer objects.
+ *
* @author Erik Brakkee
*/
public class SpringComponent extends AbstractComponent<Scope> {
- /**
- * DOCUMENT ME!
- */
private static final String CONTEXT_KEY = "context";
- /**
- * DOCUMENT ME!
- */
static final ThreadLocal<SpringComponent> THIS = new ThreadLocal<SpringComponent>();
- /**
- * DOCUMENT ME!
- */
static final ThreadLocal<Scope> SCOPE = new ThreadLocal<Scope>();
- /**
- * DOCUMENT ME!
- */
private Properties properties;
- /**
- * DOCUMENT ME!
- */
private String[] configFiles;
- /**
- * DOCUMENT ME!
- */
private Map<String, ProvidedInterface> provided;
- /**
- * DOCUMENT ME!
- */
private Map<RequiredInterface, String> required;
- /**
- * DOCUMENT ME!
- */
private Map<String, Properties> propertyObjects;
-/**
- * Constructs a spring system.
- *
- * @param aName
- * Name of the system.
- * @param aConfigFil
- * Spring config files to read.
- * @param aProvided
- * Map of bean name to service descriptor describing the bean
- * names that the spring config files use for each required
- * service.
- * @param aRequired
- * Map of bean name to service descriptor describing the bean
- * names that the spring config files use for each required
- * service.
- */
+ /**
+ * Constructs a spring system.
+ *
+ * @param aName
+ * Name of the system.
+ * @param aConfigFil
+ * Spring config files to read.
+ * @param aProvided
+ * Map of bean name to service descriptor describing the bean
+ * names that the spring config files use for each required
+ * service.
+ * @param aRequired
+ * Map of bean name to service descriptor describing the bean
+ * names that the spring config files use for each required
+ * service.
+ */
public SpringComponent(String aName, String[] aConfigFiles,
Map<String, ProvidedInterface> aProvided,
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>();
}
/**
- * Must be called to make a property available in the application
- * context.
- *
- * @param aKey Property key.
- * @param aValue Property value.
+ * Must be called to make a property available in the application context.
+ *
+ * @param aKey
+ * Property key.
+ * @param aValue
+ * Property value.
*/
public void setProperty(String aKey, String aValue) {
properties.put(aKey, aValue);
}
- /**
- * DOCUMENT ME!
- *
- * @param aProperties DOCUMENT ME!
- */
public void addProperties(Properties aProperties) {
for (Object key : aProperties.keySet()) {
setProperty((String) key, aProperties.getProperty((String) key));
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aBeanname DOCUMENT ME!
- * @param aProperties DOCUMENT ME!
- */
public void addProperties(String aBeanname, Properties aProperties) {
propertyObjects.put(aBeanname, aProperties);
}
- /**
- * DOCUMENT ME!
- *
- * @param aBeanname DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Properties getProperties(String aBeanname) {
return propertyObjects.get(aBeanname);
}
- /**
- * DOCUMENT ME!
- *
- * @param aExternalScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws SystemAssemblyException DOCUMENT ME!
- */
@Override
protected Scope doStart(Scope aExternalScope) {
- SpringComponent old = THIS.get();
- Scope oldScope = SCOPE.get();
+ SpringComponent old = THIS.get();
+ Scope oldScope = SCOPE.get();
THIS.set(this);
- Scope scope = new DefaultScope(getProvidedInterfaces()
- .toArray(new ProvidedInterface[0]), aExternalScope);
+ Scope scope = new DefaultScope(getProvidedInterfaces().toArray(
+ new ProvidedInterface[0]), aExternalScope);
SCOPE.set(scope);
try {
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aContext DOCUMENT ME!
- * @param aScope DOCUMENT ME!
- *
- * @throws IllegalArgumentException DOCUMENT ME!
- */
private void exposeProvidedServices(AbstractApplicationContext aContext,
Scope aScope) {
// Call addService for each provided service.
Object svc = aContext.getBean(name);
if (svc == null) {
- throw new IllegalArgumentException(getQualifiedName()
- + ": service '" + name + "' is null");
+ throw new IllegalArgumentException(getQualifiedName() +
+ ": service '" + name + "' is null");
}
addInterface(provided.get(name), svc, aScope);
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aParentContext DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private AbstractApplicationContext parseConfigFiles(
GenericApplicationContext aParentContext) {
// Parse spring config files
false, aParentContext);
}
- /**
- * DOCUMENT ME!
- *
- * @param aParentContext DOCUMENT ME!
- */
private void registerRequiredServices(
GenericApplicationContext aParentContext) {
// Register required services in a parent context
ConstructorArgumentValues cargs = new ConstructorArgumentValues();
cargs.addGenericArgumentValue(requiredIntf.getName());
- BeanDefinition definition = new RootBeanDefinition(RequiredServiceBean.class,
- cargs, new MutablePropertyValues());
+ BeanDefinition definition = new RootBeanDefinition(
+ RequiredServiceBean.class, cargs,
+ new MutablePropertyValues());
aParentContext.registerBeanDefinition(beanName, definition);
} else {
- // The required interface is not required by the spring config but by the sub-class directly.
+ // The required interface is not required by the spring config
+ // but by the sub-class directly.
}
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aParentContext DOCUMENT ME!
- */
private void registerPropertyObjects(
GenericApplicationContext aParentContext) {
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());
+ BeanDefinition definition = new RootBeanDefinition(
+ ConfiguredProperties.class, cargs, new MutablePropertyValues());
aParentContext.registerBeanDefinition(beanName, definition);
}
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
protected void doStop(Scope aRuntime) {
AbstractApplicationContext context = (AbstractApplicationContext) aRuntime
import java.net.URL;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
class StringResource implements Resource {
- /**
- * DOCUMENT ME!
- */
private String _value;
-/**
+ /**
* Creates a new StringResource object.
- *
- * @param aValue DOCUMENT ME!
+ *
*/
public StringResource(String aValue) {
_value = aValue;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRelativePath DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
@Override
- public Resource createRelative(String aRelativePath)
- throws IOException {
+ public Resource createRelative(String aRelativePath) throws IOException {
throw new IOException("No relative resource possible");
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean exists() {
return false;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getDescription() {
return "Properties of a spring component";
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
@Override
public File getFile() throws IOException {
throw new IOException();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public String getFilename() {
return "springcomponent.properties";
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
@Override
public URL getURL() throws IOException {
throw new IOException();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public boolean isOpen() {
return false;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(_value.getBytes());
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class DatasourceComponent extends AbstractComponent<DataSource> {
- /**
- * DOCUMENT ME!
- */
- private static RequiredInterface PROPS = new DefaultRequiredInterface("dbprops",
- Properties.class);
+ private static RequiredInterface PROPS = new DefaultRequiredInterface(
+ "dbprops", Properties.class);
- /**
- * DOCUMENT ME!
- */
- private static ProvidedInterface DATASOURCE = new DefaultProvidedInterface("datasource",
- DataSource.class);
+ private static ProvidedInterface DATASOURCE = new DefaultProvidedInterface(
+ "datasource", DataSource.class);
- /**
- * DOCUMENT ME!
- */
- private static ProvidedInterface ORM_CONFIG = new DefaultProvidedInterface("ormconfig",
- ORMappingConfig.class);
+ private static ProvidedInterface ORM_CONFIG = new DefaultProvidedInterface(
+ "ormconfig", ORMappingConfig.class);
-/**
+ /**
* Creates a new DatasourceComponent object.
- *
- * @param aName DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
+ *
+ *
*/
public DatasourceComponent(String aName) throws IOException {
super(aName);
addProvidedInterface(ORM_CONFIG);
}
- /**
- * DOCUMENT ME!
- *
- * @param aScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected DataSource doStart(Scope aScope) {
- Properties dbProps = aScope.getInterfaceImplementation(PROPS
- .getProvider(), Properties.class);
- DriverManagerDataSource ds = new DriverManagerDataSource(dbProps
- .getProperty("database.url"),
- dbProps.getProperty("database.username"),
- dbProps.getProperty("database.password"));
+ Properties dbProps = aScope.getInterfaceImplementation(PROPS
+ .getProvider(), Properties.class);
+ DriverManagerDataSource ds = new DriverManagerDataSource(dbProps
+ .getProperty("database.url"), dbProps
+ .getProperty("database.username"), dbProps
+ .getProperty("database.password"));
addInterface(DATASOURCE, ds, aScope);
- DatabaseType type = DatabaseType.valueOf(dbProps.getProperty(
- "database.type"));
+ DatabaseType type = DatabaseType.valueOf(dbProps
+ .getProperty("database.type"));
ORMappingConfig config = new ORMappingConfig(true, type);
return ds;
}
- /**
- * DOCUMENT ME!
- *
- * @param aRuntime DOCUMENT ME!
- */
@Override
protected void doStop(DataSource aRuntime) {
// Empty.
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class HibernateComponent extends SpringComponent {
- /**
- * DOCUMENT ME!
- */
private static final String HIBERNATE_DIALECT_PROP = "hibernate.dialect";
- /**
- * DOCUMENT ME!
- */
private static final String HIBERNATE_SCHEMAUPDATE_PROP = "hibernate.schemaupdate";
- /**
- * DOCUMENT ME!
- */
private static final String HIBERNATE_PROPS_KEY = "hibernateProperties";
- /**
- * DOCUMENT ME!
- */
private static final String HIBERNATE_SPRING_CONFIG = "spring/org.wamblee.system.spring.component.hibernate.xml";
- /**
- * DOCUMENT ME!
- */
- private final RequiredInterface CONFIG = new DefaultRequiredInterface("config",
- ORMappingConfig.class);
+ private final RequiredInterface CONFIG = new DefaultRequiredInterface(
+ "config", ORMappingConfig.class);
-/**
+ /**
* Creates a new HibernateComponent object.
- *
- * @param aName DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
+ *
+ *
*/
public HibernateComponent(String aName) throws IOException {
super(aName, new String[] { HIBERNATE_SPRING_CONFIG },
addRequiredInterface(CONFIG);
}
- /**
- * DOCUMENT ME!
- *
- * @param aExternalScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Scope doStart(Scope aExternalScope) {
- ORMappingConfig config = aExternalScope.getInterfaceImplementation(CONFIG
- .getProvider(), ORMappingConfig.class);
+ ORMappingConfig config = aExternalScope.getInterfaceImplementation(
+ CONFIG.getProvider(), ORMappingConfig.class);
setProperty(HIBERNATE_SCHEMAUPDATE_PROP, "" + config.isSchemaUpdate());
- DatabaseType db = config.getType();
- String dialect = db.handleCases(new DatabaseType.Switch<String>() {
- @Override
- public String handleMySqlInnoDb() {
- return MySQLInnoDBDialect.class.getName();
- }
+ DatabaseType db = config.getType();
+ String dialect = db.handleCases(new DatabaseType.Switch<String>() {
+ @Override
+ public String handleMySqlInnoDb() {
+ return MySQLInnoDBDialect.class.getName();
+ }
- @Override
- public String handleDerby() {
- return DerbyDialect.class.getName();
- }
- });
+ @Override
+ public String handleDerby() {
+ return DerbyDialect.class.getName();
+ }
+ });
getHibernateProperties().put(HIBERNATE_DIALECT_PROP, dialect);
return super.doStart(aExternalScope);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private Properties getHibernateProperties() {
return getProperties(HIBERNATE_PROPS_KEY);
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static Map<RequiredInterface, String> createRequired() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
- required.put(new DefaultRequiredInterface("datasource", DataSource.class),
- "dataSource");
+ required.put(new DefaultRequiredInterface("datasource",
+ DataSource.class), "dataSource");
required.put(new DefaultRequiredInterface("mappingFiles",
- HibernateMappingFiles.class), "hibernateMappingFiles");
+ HibernateMappingFiles.class), "hibernateMappingFiles");
return required;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private static Map<String, ProvidedInterface> createProvided() {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("transactionManager",
- new DefaultProvidedInterface("transactionMgr",
- PlatformTransactionManager.class));
- provided.put("sessionFactory",
- new DefaultProvidedInterface("sessionFactory", SessionFactory.class));
+ provided.put("transactionManager", new DefaultProvidedInterface(
+ "transactionMgr", PlatformTransactionManager.class));
+ provided.put("sessionFactory", new DefaultProvidedInterface(
+ "sessionFactory", SessionFactory.class));
provided.put("org.springframework.orm.hibernate3.HibernateTemplate",
new DefaultProvidedInterface("hibernateTemplate",
HibernateTemplate.class));
package org.wamblee.system.spring;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class BlaService {
- /**
- * DOCUMENT ME!
- */
private HelloService hello;
-/**
+ /**
* Creates a new BlaService object.
- *
- * @param aService DOCUMENT ME!
+ *
*/
public BlaService(HelloService aService) {
if (aService == null) {
hello = aService;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String execute() {
return hello.say();
}
- /**
- * DOCUMENT ME!
- */
public void stop() {
System.out.println("Blaservice stopping");
}
import java.util.Properties;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class ConfiguredPropertiesTest extends TestCase {
- /**
- * DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
public void testProps() throws IOException {
Properties props = new Properties();
props.put("x", "y");
props.put("a", "b");
ConfiguredProperties props2 = new ConfiguredProperties(PropertySetter
- .createPropertyFile(props));
+ .createPropertyFile(props));
assertEquals(props.size(), props2.size());
assertEquals(props.get("x"), props2.get("x"));
package org.wamblee.system.spring;
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class HelloService {
- /**
- * DOCUMENT ME!
- */
private String msg;
-/**
+ /**
* Creates a new HelloService object.
- *
- * @param aMsg DOCUMENT ME!
+ *
*/
public HelloService(String aMsg) {
SpringComponentTest.EVENT_TRACKER.eventOccurred(aMsg);
msg = aMsg;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public String say() {
return msg;
}
import java.util.Properties;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class HelloService2 {
- /**
- * DOCUMENT ME!
- */
private Properties props;
-/**
+ /**
* Creates a new HelloService2 object.
- *
- * @param aProps DOCUMENT ME!
+ *
*/
public HelloService2(Properties aProps) {
props = aProps;
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Properties getProperties() {
return props;
}
import java.util.Map;
import java.util.Properties;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class SpringComponentTest extends TestCase {
- /**
- * DOCUMENT ME!
- */
private static final String HELLO_SERVICE_SPRING_XML = "test.org.wamblee.system.spring.xml";
- /**
- * DOCUMENT ME!
- */
private static final String HELLO_SERVICE_SPRING_WITH_REQS_XML = "test.org.wamblee.system.springWithRequirements.xml";
- /**
- * DOCUMENT ME!
- */
private static final String HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML = "test.org.wamblee.system.springWithProperties.xml";
- /**
- * DOCUMENT ME!
- */
private static final String HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML2 = "test.org.wamblee.system.springWithProperties2.xml";
- /**
- * DOCUMENT ME!
- */
private static final String PROPERTY_FILE = "test.org.wamblee.system.spring.properties";
- /**
- * DOCUMENT ME!
- */
public static EventTracker<String> EVENT_TRACKER;
- /**
- * DOCUMENT ME!
- */
private Scope externalScope;
- /**
- * DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
@Override
protected void setUp() throws Exception {
super.setUp();
- EVENT_TRACKER = new EventTracker<String>();
- externalScope = new DefaultScope(new ProvidedInterface[0]);
+ EVENT_TRACKER = new EventTracker<String>();
+ externalScope = new DefaultScope(new ProvidedInterface[0]);
}
- /**
- * DOCUMENT ME!
- */
public void testBlackboxSystem() {
- SpringComponent system = new SpringComponent("system",
- new String[] { HELLO_SERVICE_SPRING_XML },
- new HashMap<String, ProvidedInterface>(),
- new HashMap<RequiredInterface, String>());
+ SpringComponent system = new SpringComponent("system",
+ new String[] { HELLO_SERVICE_SPRING_XML },
+ new HashMap<String, ProvidedInterface>(),
+ new HashMap<RequiredInterface, String>());
- Scope runtime = system.start(externalScope);
+ Scope runtime = system.start(externalScope);
assertEquals(0, externalScope.getProvidedInterfaces().size());
system.stop(runtime);
}
- /**
- * DOCUMENT ME!
- */
public void testOneProvidedService() {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("helloService",
- new DefaultProvidedInterface("hello", HelloService.class));
+ provided.put("helloService", new DefaultProvidedInterface("hello",
+ HelloService.class));
- SpringComponent system = new SpringComponent("system",
- new String[] { HELLO_SERVICE_SPRING_XML }, provided,
- new HashMap<RequiredInterface, String>());
- Scope runtime = system.start(externalScope);
+ SpringComponent system = new SpringComponent("system",
+ new String[] { HELLO_SERVICE_SPRING_XML }, provided,
+ new HashMap<RequiredInterface, String>());
+ Scope runtime = system.start(externalScope);
List<ProvidedInterface> services = runtime.getProvidedInterfaces();
assertEquals(1, services.size());
Object service = runtime.getInterfaceImplementation(services.get(0),
- Object.class);
+ Object.class);
assertTrue(service instanceof HelloService);
// BUG; Provided services should be made available in the external
// scope.
- Object service2 = externalScope.getInterfaceImplementation(provided.get(
- "helloService"), Object.class);
+ Object service2 = externalScope.getInterfaceImplementation(provided
+ .get("helloService"), Object.class);
assertSame(service, service2);
assertEquals("Hello world!", ((HelloService) service).say());
system.stop(runtime);
}
- /**
- * DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
public void testWithProperties() throws IOException {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("helloService",
- new DefaultProvidedInterface("hello", HelloService.class));
+ provided.put("helloService", new DefaultProvidedInterface("hello",
+ HelloService.class));
SpringComponent system = new SpringComponent("system",
- new String[] { HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML },
- provided, new HashMap<RequiredInterface, String>());
- Properties props = new Properties();
+ new String[] { HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML },
+ provided, new HashMap<RequiredInterface, String>());
+ Properties props = new Properties();
props.load(new ClassPathResource(PROPERTY_FILE).getInputStream());
system.addProperties(props);
assertEquals(1, EVENT_TRACKER.getEventCount());
List<ProvidedInterface> services = scope.getProvidedInterfaces();
- assertEquals("Property Value",
- scope.getInterfaceImplementation(services.get(0), HelloService.class)
- .say());
+ assertEquals("Property Value", scope.getInterfaceImplementation(
+ services.get(0), HelloService.class).say());
}
- /**
- * DOCUMENT ME!
- *
- * @throws IOException DOCUMENT ME!
- */
public void testWithPropertiesAsBean() throws IOException {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("helloService",
- new DefaultProvidedInterface("hello", HelloService2.class));
+ provided.put("helloService", new DefaultProvidedInterface("hello",
+ HelloService2.class));
SpringComponent system = new SpringComponent("system",
- new String[] { HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML2 },
- provided, new HashMap<RequiredInterface, String>());
- Properties props = new Properties();
+ new String[] { HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML2 },
+ provided, new HashMap<RequiredInterface, String>());
+ Properties props = new Properties();
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();
- Properties props2 = scope.getInterfaceImplementation(services
- .get(0), HelloService2.class).getProperties();
+ Properties props2 = scope.getInterfaceImplementation(services.get(0),
+ HelloService2.class).getProperties();
assertEquals(props, props2);
}
- /**
- * DOCUMENT ME!
- */
public void testWithMissingRequirement() {
try {
SpringComponent system = new SpringComponent("system",
- new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
- new HashMap<String, ProvidedInterface>(),
- new HashMap<RequiredInterface, String>());
+ new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
+ new HashMap<String, ProvidedInterface>(),
+ new HashMap<RequiredInterface, String>());
system.start(externalScope);
} catch (SystemAssemblyException e) {
// e.printStackTrace();
fail();
}
- /**
- * DOCUMENT ME!
- */
public void testWithRequirement() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
required.put(new DefaultRequiredInterface("hello", HelloService.class),
"helloService");
- SpringComponent system = new SpringComponent("system",
- new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
- new HashMap<String, ProvidedInterface>(), required);
+ SpringComponent system = new SpringComponent("system",
+ new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
+ new HashMap<String, ProvidedInterface>(), required);
- HelloService helloObject = new HelloService("ladida");
+ HelloService helloObject = new HelloService("ladida");
ProvidedInterface helloService = new DefaultProvidedInterface("hello",
- HelloService.class);
- Scope scope = new DefaultScope(new ProvidedInterface[] {
- helloService
- });
+ HelloService.class);
+ Scope scope = new DefaultScope(new ProvidedInterface[] { helloService });
scope.publishInterface(helloService, helloObject);
system.getRequiredInterfaces().get(0).setProvider(helloService);
system.stop(runtime);
}
- /**
- * DOCUMENT ME!
- */
public void testWithRequirementAndProvidedService() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
required.put(new DefaultRequiredInterface("hello", HelloService.class),
"helloService");
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("blaService",
- new DefaultProvidedInterface("bla", BlaService.class));
+ provided.put("blaService", new DefaultProvidedInterface("bla",
+ BlaService.class));
- SpringComponent system = new SpringComponent("system",
- new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, provided,
- required);
+ SpringComponent system = new SpringComponent("system",
+ new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, provided,
+ required);
- HelloService helloObject = new HelloService("ladida");
+ HelloService helloObject = new HelloService("ladida");
ProvidedInterface helloService = new DefaultProvidedInterface("hello",
- HelloService.class);
- Scope scope = new DefaultScope(new ProvidedInterface[] {
- helloService
- });
+ HelloService.class);
+ Scope scope = new DefaultScope(new ProvidedInterface[] { helloService });
scope.publishInterface(helloService, helloObject);
system.getRequiredInterfaces().get(0).setProvider(helloService);
- Scope runtime = system.start(scope);
+ Scope runtime = system.start(scope);
ProvidedInterface started = runtime.getProvidedInterfaces().get(0);
- Object impl = runtime.getInterfaceImplementation(started,
- BlaService.class);
+ Object impl = runtime.getInterfaceImplementation(started,
+ BlaService.class);
assertNotNull(impl);
assertTrue(impl instanceof BlaService);
assertEquals("ladida", ((BlaService) impl).execute());
}
/**
- * Tests a scenario where a subclass of SpringComponent adds a new
- * provided interface where the interface is provided by the subclass
- * itself and not by the spring configs inside.
+ * Tests a scenario where a subclass of SpringComponent adds a new provided
+ * interface where the interface is provided by the subclass itself and not
+ * by the spring configs inside.
*/
public void testWithProvidedFromSubClassNotFromConfig() {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("helloService",
- new DefaultProvidedInterface("hello", HelloService.class));
+ provided.put("helloService", new DefaultProvidedInterface("hello",
+ HelloService.class));
- SubSpringComponent system = new SubSpringComponent("system",
- new String[] { HELLO_SERVICE_SPRING_XML }, provided,
- new HashMap<RequiredInterface, String>());
+ SubSpringComponent system = new SubSpringComponent("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(2, services.size());
Object service = runtime.getInterfaceImplementation(services.get(0),
- Object.class);
+ Object.class);
assertTrue(service instanceof HelloService);
// BUG; Provided services should be made available in the external
// scope.
- Object service2 = externalScope.getInterfaceImplementation(provided.get(
- "helloService"), Object.class);
+ Object service2 = externalScope.getInterfaceImplementation(provided
+ .get("helloService"), Object.class);
assertSame(service, service2);
- Object floatsvc = externalScope.getInterfaceImplementation(system.getProvidedInterfaces()
- .get(1), Object.class);
+ Object floatsvc = externalScope.getInterfaceImplementation(system
+ .getProvidedInterfaces().get(1), Object.class);
assertTrue(floatsvc instanceof Float);
assertTrue((((Float) floatsvc).floatValue() - 100.345f) < 0.00001);
}
/**
- * Tests the spring component with an additional requirement from
- * the subclass which is not required by the spring config files inside.
+ * Tests the spring component with an additional requirement from the
+ * subclass which is not required by the spring config files inside.
*/
public void testWithRequirementFromSubClass() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
required.put(new DefaultRequiredInterface("hello", HelloService.class),
"helloService");
- SpringComponent system = new SubSpringComponent2("system",
- new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
- new HashMap<String, ProvidedInterface>(), required);
+ SpringComponent system = new SubSpringComponent2("system",
+ new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
+ new HashMap<String, ProvidedInterface>(), required);
- HelloService helloObject = new HelloService("ladida");
+ HelloService helloObject = new HelloService("ladida");
ProvidedInterface helloService = new DefaultProvidedInterface("hello",
- HelloService.class);
+ HelloService.class);
ProvidedInterface floatService = new DefaultProvidedInterface("float",
- Float.class);
+ Float.class);
- Scope scope = new DefaultScope(new ProvidedInterface[] {
- helloService
- });
+ Scope scope = new DefaultScope(new ProvidedInterface[] { helloService });
scope.publishInterface(helloService, helloObject);
scope.publishInterface(floatService, 100.234f);
system.getRequiredInterfaces().get(0).setProvider(helloService);
import java.util.Map;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class SubSpringComponent extends SpringComponent {
- /**
- * DOCUMENT ME!
- */
- private static ProvidedInterface PROVIDED = new DefaultProvidedInterface("provided",
- Float.class);
+ private static ProvidedInterface PROVIDED = new DefaultProvidedInterface(
+ "provided", Float.class);
-/**
+ /**
* Creates a new SubSpringComponent object.
- *
- * @param aName DOCUMENT ME!
- * @param aConfigFiles DOCUMENT ME!
- * @param aProvided DOCUMENT ME!
- * @param aRequired DOCUMENT ME!
+ *
*/
public SubSpringComponent(String aName, String[] aConfigFiles,
Map<String, ProvidedInterface> aProvided,
addProvidedInterface(PROVIDED);
}
- /**
- * DOCUMENT ME!
- *
- * @param aExternalScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Scope doStart(Scope aExternalScope) {
Scope scope = super.doStart(aExternalScope);
import java.util.Map;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class SubSpringComponent2 extends SpringComponent {
- /**
- * DOCUMENT ME!
- */
- private static RequiredInterface REQUIRED = new DefaultRequiredInterface("required",
- Float.class);
+ private static RequiredInterface REQUIRED = new DefaultRequiredInterface(
+ "required", Float.class);
-/**
+ /**
* Creates a new SubSpringComponent2 object.
- *
- * @param aName DOCUMENT ME!
- * @param aConfigFiles DOCUMENT ME!
- * @param aProvided DOCUMENT ME!
- * @param aRequired DOCUMENT ME!
+ *
*/
public SubSpringComponent2(String aName, String[] aConfigFiles,
Map<String, ProvidedInterface> aProvided,
addRequiredInterface(REQUIRED);
}
- /**
- * DOCUMENT ME!
- *
- * @param aExternalScope DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected Scope doStart(Scope aExternalScope) {
Scope scope = super.doStart(aExternalScope);
float value = aExternalScope.getInterfaceImplementation(REQUIRED
- .getProvider(), Float.class);
+ .getProvider(), Float.class);
scope.put("floatValue", value);
return scope;
import javax.sql.DataSource;
-
/**
- * Test support class for database testing. Currently, this still requires
- * the spring platform transaction manager and hibernate template.
+ * Test support class for database testing. Currently, this still requires the
+ * spring platform transaction manager and hibernate template.
*/
public class DatabaseTesterComponent {
- /**
- * DOCUMENT ME!
- */
- private static final Log LOG = LogFactory.getLog(DatabaseTesterComponent.class);
+ private static final Log LOG = LogFactory
+ .getLog(DatabaseTesterComponent.class);
/**
* Schema pattern.
*/
private ApplicationContext context;
- /**
- * DOCUMENT ME!
- */
private HibernateTemplate hibernateTemplate;
- /**
- * DOCUMENT ME!
- */
private PlatformTransactionManager transactionManager;
- /**
- * DOCUMENT ME!
- */
private DataSource dataSource;
-/**
+ /**
* Creates a new DatabaseTesterComponent object.
- *
- * @param aHibernateTemplate DOCUMENT ME!
- * @param aTransactionManager DOCUMENT ME!
- * @param aDataSource DOCUMENT ME!
+ *
*/
public DatabaseTesterComponent(HibernateTemplate aHibernateTemplate,
PlatformTransactionManager aTransactionManager, DataSource aDataSource) {
- hibernateTemplate = aHibernateTemplate;
- transactionManager = aTransactionManager;
- dataSource = aDataSource;
+ hibernateTemplate = aHibernateTemplate;
+ transactionManager = aTransactionManager;
+ dataSource = aDataSource;
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Hibernate session factory.
*/
protected SessionFactory getSessionFactory() {
/**
* Performs common initialization for test cases:
- * <ul>
- * <li>Cleaning the database.</li>
- * </ul>
- *
+ * <ul>
+ * <li>Cleaning the database.</li>
+ * </ul>
+ *
* @throws Exception
*/
public void setUp() throws Exception {
}
/**
- * Performs common tear down after execution of a test case.
- * Currenlty this method does nothing.
- *
+ * Performs common tear down after execution of a test case. Currenlty this
+ * method does nothing.
+ *
* @throws Exception
*/
protected void tearDown() throws Exception {
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Transaction manager
*/
protected PlatformTransactionManager getTransactionManager() {
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Starts a new transaction.
*/
protected TransactionStatus getTransaction() {
/**
* Returns the hibernate template for executing hibernate-specific
* functionality.
- *
+ *
* @return Hibernate template.
*/
public HibernateTemplate getTemplate() {
}
/**
- * Flushes the session. Should be called after some Hibernate work
- * and before JDBC is used to check results.
+ * Flushes the session. Should be called after some Hibernate work and
+ * before JDBC is used to check results.
*/
public void flush() {
getTemplate().flush();
}
/**
- * Flushes the session first and then removes all objects from the
- * Session cache. Should be called after some Hibernate work and before
- * JDBC is used to check results.
+ * Flushes the session first and then removes all objects from the Session
+ * cache. Should be called after some Hibernate work and before JDBC is used
+ * to check results.
*/
public void clear() {
flush();
/**
* Evicts the object from the session. This is essential for the
* implementation of unit tests where first an object is saved and is
- * retrieved later. By removing the object from the session, Hibernate
- * must retrieve the object again from the database.
- *
+ * retrieved later. By removing the object from the session, Hibernate must
+ * retrieve the object again from the database.
+ *
* @param aObject
*/
protected void evict(Object aObject) {
/**
* Gets the connection.
- *
+ *
* @return Connection.
*/
public Connection getConnection() {
return DataSourceUtils.getConnection(getDataSource());
}
- /**
- * DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
- */
public void cleanDatabase() throws SQLException {
if (!isDatabaseConfigured()) {
return;
String[] tables = getTableNames();
try {
- IDatabaseConnection connection = new DatabaseConnection(getConnection());
- ITableFilter filter = new DatabaseSequenceFilter(connection,
- tables);
- IDataSet dataset = new FilteredDataSet(filter,
- connection.createDataSet(tables));
+ IDatabaseConnection connection = new DatabaseConnection(
+ getConnection());
+ ITableFilter filter = new DatabaseSequenceFilter(connection, tables);
+ IDataSet dataset = new FilteredDataSet(filter, connection
+ .createDataSet(tables));
DatabaseOperation.DELETE_ALL.execute(connection, dataset);
} catch (DatabaseUnitException e) {
}
/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
+ *
+ *
* @throws SQLException
*/
public String[] getTableNames() throws SQLException {
List<String> result = new ArrayList<String>();
- LOG.debug("Getting database table names to clean (schema: '"
- + SCHEMA_PATTERN + "'");
+ LOG.debug("Getting database table names to clean (schema: '" +
+ SCHEMA_PATTERN + "'");
- ResultSet tables = getConnection().getMetaData()
- .getTables(null, SCHEMA_PATTERN, "%", new String[] { "TABLE" });
+ ResultSet tables = getConnection().getMetaData().getTables(null,
+ SCHEMA_PATTERN, "%", new String[] { "TABLE" });
while (tables.next()) {
String table = tables.getString("TABLE_NAME");
// infrastructure tables.
if (!table.toLowerCase().startsWith("hibernate")) {
result.add(table);
- LOG.debug("Adding " + table
- + " to list of tables to be cleaned.");
+ LOG.debug("Adding " + table +
+ " to list of tables to be cleaned.");
}
}
}
/**
- * DOCUMENT ME!
- *
- * @param aTableList DOCUMENT ME!
- *
+ *
+ *
* @throws SQLException
*/
public void emptyTables(List aTableList) throws SQLException {
}
/**
- * DOCUMENT ME!
- *
- * @param aTable DOCUMENT ME!
- *
+ *
+ *
* @throws SQLException
*/
public void emptyTable(String aTable) throws SQLException {
}
/**
- * DOCUMENT ME!
- *
- * @param aTable DOCUMENT ME!
- *
+ *
+ *
* @throws SQLException
*/
public void dropTable(String aTable) throws SQLException {
/**
* Executes an SQL statement within a transaction.
- *
- * @param aSql SQL statement.
- *
+ *
+ * @param aSql
+ * SQL statement.
+ *
* @return Return code of the corresponding JDBC call.
*/
public int executeSql(final String aSql) {
}
/**
- * Executes an SQL statement within a transaction. See {@link
- * #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * Executes an SQL statement within a transaction. See
+ * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
* supported argument types.
- *
- * @param aSql SQL statement.
- * @param aArg Argument of the sql statement.
- *
+ *
+ * @param aSql
+ * SQL statement.
+ * @param aArg
+ * Argument of the sql statement.
+ *
* @return Return code of the corresponding JDBC call.
*/
public int executeSql(final String aSql, final Object aArg) {
}
/**
- * Executes an sql statement. See {@link #setPreparedParam(int,
- * PreparedStatement, Object)}for details on supported argument types.
- *
- * @param aSql SQL query to execute.
- * @param aArgs Arguments.
- *
+ * Executes an sql statement. See
+ * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * supported argument types.
+ *
+ * @param aSql
+ * SQL query to execute.
+ * @param aArgs
+ * Arguments.
+ *
* @return Number of rows updated.
*/
public int executeSql(final String aSql, final Object[] aArgs) {
Map results = executeTransaction(new TestTransactionCallback() {
- public Map execute() throws Exception {
- JdbcTemplate template = new JdbcTemplate(getDataSource());
- int result = template.update(aSql,
- aArgs);
+ public Map execute() throws Exception {
+ JdbcTemplate template = new JdbcTemplate(getDataSource());
+ int result = template.update(aSql, aArgs);
- Map<String, Integer> map = new TreeMap<String, Integer>();
- map.put("result", new Integer(result));
+ Map<String, Integer> map = new TreeMap<String, Integer>();
+ map.put("result", new Integer(result));
- return map;
- }
- });
+ return map;
+ }
+ });
return ((Integer) results.get("result")).intValue();
}
/**
* Executes a transaction with a result.
- *
- * @param aCallback Callback to do your transactional work.
- *
+ *
+ * @param aCallback
+ * Callback to do your transactional work.
+ *
* @return Result.
*/
public Object executeTransaction(TransactionCallback aCallback) {
- TransactionTemplate lTemplate = new TransactionTemplate(getTransactionManager());
+ TransactionTemplate lTemplate = new TransactionTemplate(
+ getTransactionManager());
return lTemplate.execute(aCallback);
}
/**
* Executes a transaction without a result.
- *
- * @param aCallback Callback to do your transactional work. .
+ *
+ * @param aCallback
+ * Callback to do your transactional work. .
*/
public void executeTransaction(TransactionCallbackWithoutResult aCallback) {
- TransactionTemplate template = new TransactionTemplate(getTransactionManager());
+ TransactionTemplate template = new TransactionTemplate(
+ getTransactionManager());
template.execute(aCallback);
}
/**
- * Executes a transaction with a result, causing the testcase to
- * fail if any type of exception is thrown.
- *
- * @param aCallback Code to be executed within the transaction.
- *
+ * Executes a transaction with a result, causing the testcase to fail if any
+ * type of exception is thrown.
+ *
+ * @param aCallback
+ * Code to be executed within the transaction.
+ *
* @return Result.
- *
- * @throws RuntimeException DOCUMENT ME!
+ *
*/
public Map executeTransaction(final TestTransactionCallback aCallback) {
return (Map) executeTransaction(new TransactionCallback() {
- public Object doInTransaction(TransactionStatus aArg) {
- try {
- return aCallback.execute();
- } catch (Exception e) {
- // test case must fail.
- e.printStackTrace();
- throw new RuntimeException(e);
- }
+ public Object doInTransaction(TransactionStatus aArg) {
+ try {
+ return aCallback.execute();
+ } catch (Exception e) {
+ // test case must fail.
+ e.printStackTrace();
+ throw new RuntimeException(e);
}
- });
+ }
+ });
}
/**
- * Executes a transaction with a result, causing the testcase to
- * fail if any type of exception is thrown.
- *
- * @param aCallback Code to be executed within the transaction.
- *
- * @throws RuntimeException DOCUMENT ME!
+ * Executes a transaction with a result, causing the testcase to fail if any
+ * type of exception is thrown.
+ *
+ * @param aCallback
+ * Code to be executed within the transaction.
+ *
*/
public void executeTransaction(
final TestTransactionCallbackWithoutResult aCallback) {
executeTransaction(new TransactionCallbackWithoutResult() {
- public void doInTransactionWithoutResult(TransactionStatus aArg) {
- try {
- aCallback.execute();
- } catch (Exception e) {
- // test case must fail.
- throw new RuntimeException(e.getMessage(), e);
- }
+ public void doInTransactionWithoutResult(TransactionStatus aArg) {
+ try {
+ aCallback.execute();
+ } catch (Exception e) {
+ // test case must fail.
+ throw new RuntimeException(e.getMessage(), e);
}
- });
+ }
+ });
}
/**
* Executes an SQL query.
- *
- * @param aSql Query to execute.
- *
+ *
+ * @param aSql
+ * Query to execute.
+ *
* @return Result set.
*/
public ResultSet executeQuery(String aSql) {
}
/**
- * Executes a query with a single argument. See {@link
- * #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * Executes a query with a single argument. See
+ * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
* supported argument types.
- *
- * @param aSql Query.
- * @param aArg Argument.
- *
+ *
+ * @param aSql
+ * Query.
+ * @param aArg
+ * Argument.
+ *
* @return Result set.
*/
public ResultSet executeQuery(String aSql, Object aArg) {
}
/**
- * Executes a query. See {@link #setPreparedParam(int,
- * PreparedStatement, Object)}for details on supported argument types.
- *
- * @param aSql Sql query.
- * @param aArgs Arguments to the query.
- *
+ * Executes a query. See
+ * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * supported argument types.
+ *
+ * @param aSql
+ * Sql query.
+ * @param aArgs
+ * Arguments to the query.
+ *
* @return Result set.
- *
- * @throws RuntimeException DOCUMENT ME!
+ *
*/
public ResultSet executeQuery(final String aSql, final Object[] aArgs) {
try {
- Connection connection = getConnection();
+ Connection connection = getConnection();
- PreparedStatement statement = connection.prepareStatement(aSql);
+ PreparedStatement statement = connection.prepareStatement(aSql);
setPreparedParams(aArgs, statement);
return statement.executeQuery();
}
/**
- * Sets the values of a prepared statement. See {@link
- * #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * Sets the values of a prepared statement. See
+ * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
* supported argument types.
- *
- * @param aArgs Arguments to the prepared statement.
- * @param aStatement Prepared statement
- *
+ *
+ * @param aArgs
+ * Arguments to the prepared statement.
+ * @param aStatement
+ * Prepared statement
+ *
* @throws SQLException
*/
private void setPreparedParams(final Object[] aArgs,
/**
* Sets a prepared statement parameter.
- *
- * @param aIndex Index of the parameter.
- * @param aStatement Prepared statement.
- * @param aObject Value Must be of type Integer, Long, or String.
- *
+ *
+ * @param aIndex
+ * Index of the parameter.
+ * @param aStatement
+ * Prepared statement.
+ * @param aObject
+ * Value Must be of type Integer, Long, or String.
+ *
* @throws SQLException
*/
private void setPreparedParam(int aIndex, PreparedStatement aStatement,
} else if (aObject instanceof String) {
aStatement.setString(aIndex, (String) aObject);
} else {
- TestCase.fail("Unsupported object type for prepared statement: "
- + aObject.getClass() + " value: " + aObject + " statement: "
- + aStatement);
+ TestCase.fail("Unsupported object type for prepared statement: " +
+ aObject.getClass() + " value: " + aObject + " statement: " +
+ aStatement);
}
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
private boolean isDatabaseConfigured() {
try {
getDataSource();
}
/**
- * DOCUMENT ME!
- *
+ *
* @return Returns the dataSource.
*/
public DataSource getDataSource() {
}
/**
- * DOCUMENT ME!
- *
- * @param aTable DOCUMENT ME!
- *
+ *
+ *
* @return
- *
+ *
* @throws SQLException
*/
public int getTableSize(final String aTable) throws SQLException {
ResultSet resultSet = executeQuery("select * from " + aTable);
- int count = 0;
+ int count = 0;
while (resultSet.next()) {
count++;
return count;
}
- /**
- * DOCUMENT ME!
- *
- * @param aResultSet DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws SQLException DOCUMENT ME!
- */
public int countResultSet(ResultSet aResultSet) throws SQLException {
int count = 0;
import java.util.Map;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class EclipselinkJpaCustomizer implements JpaCustomizer {
-/**
+ /**
* Creates a new EclipselinkJpaCustomizer object.
*/
public EclipselinkJpaCustomizer() {
// Empty
}
- /**
- * DOCUMENT ME!
- *
- * @param aPersistenceUnit DOCUMENT ME!
- * @param aJpaProperties DOCUMENT ME!
- */
@Override
public void customize(PersistenceUnitDescription aPersistenceUnit,
Map<String, String> aJpaProperties) {
aJpaProperties.put("eclipselink.ddl-generation", "create-tables");
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public ITableFilterSimple getJpaTables() {
return new EclipselinkTables();
import java.util.Arrays;
import java.util.List;
-
/**
* Toplink-specific tables.
*/
public class EclipselinkTables implements ITableFilterSimple {
- /**
- * DOCUMENT ME!
- */
- private static final List<String> TABLES = Arrays.asList(new String[] {
- "SEQUENCE"
- });
+ private static final List<String> TABLES = Arrays
+ .asList(new String[] { "SEQUENCE" });
- /**
- * DOCUMENT ME!
- *
- * @param aTableName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws DataSetException DOCUMENT ME!
- */
public boolean accept(String aTableName) throws DataSetException {
return TABLES.contains(aTableName);
}
import javax.naming.Context;
import javax.naming.InitialContext;
-
/**
- * See
- * http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use
- * for clients that would like to use a JTA SE pu instead of a RESOURCE_LOCAL
- * SE pu. This utility also makes sure that using a persistence.xml with a
- * JTA datasource works in a standalone Java SE environment together with our
- * JNDI stub.
+ * See http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG)
+ * Use for clients that would like to use a JTA SE pu instead of a
+ * RESOURCE_LOCAL SE pu. This utility also makes sure that using a
+ * persistence.xml with a JTA datasource works in a standalone Java SE
+ * environment together with our JNDI stub.
*/
public class JndiSessionCustomizer implements SessionCustomizer {
-/**
+ /**
* Creates a new JndiSessionCustomizer object.
*/
public JndiSessionCustomizer() {
/**
* Get a dataSource connection and set it on the session with
* lookupType=STRING_LOOKUP
- *
- * @param session DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
+ *
+ *
*/
public void customize(Session session) throws Exception {
JNDIConnector connector = null;
- Context context = null;
+ Context context = null;
try {
context = new InitialContext();
if (null != context) {
- connector = (JNDIConnector) session.getLogin().getConnector(); // possible CCE
- // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
- // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in
- // the COMPOSITE_NAME_LOOKUP being set
- // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
+ connector = (JNDIConnector) session.getLogin().getConnector(); // possible
+ // CCE
+ // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
+ // Note: if both jta and non-jta elements exist this will only
+ // change the first one - and may still result in
+ // the COMPOSITE_NAME_LOOKUP being set
+ // Make sure only jta-data-source is in persistence.xml with no
+ // non-jta-data-source property set
connector.setLookupType(JNDIConnector.STRING_LOOKUP);
- // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
- JNDIConnector writeConnector = (JNDIConnector) session.getLogin()
- .getConnector();
+ // Or, if you are specifying both JTA and non-JTA in your
+ // persistence.xml then set both connectors to be safe
+ JNDIConnector writeConnector = (JNDIConnector) session
+ .getLogin().getConnector();
writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
- JNDIConnector readConnector = (JNDIConnector) ((DatabaseLogin) ((ServerSession) session).getReadConnectionPool()
- .getLogin()).getConnector();
+ JNDIConnector readConnector = (JNDIConnector) ((DatabaseLogin) ((ServerSession) session)
+ .getReadConnectionPool().getLogin()).getConnector();
readConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
- System.out.println("JndiSessionCustomizer: configured "
- + connector.getName());
+ System.out.println("JndiSessionCustomizer: configured " +
+ connector.getName());
} else {
throw new Exception("JndiSessionCustomizer: Context is null");
}
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
import javax.sql.DataSource;
-
/**
- * This class shows an example of how to test an entity using jpa.
+ * This class shows an example of how to test an entity using jpa.
*/
public class MyEntityExampleTest extends MyEntityExampleTestBase {
// Empty, all tests are inherited
import javax.naming.NamingException;
public class StubInitialContext extends InitialContext {
- private Map<String, Object> bindings = new HashMap<String, Object>();
+ private Map<String, Object> bindings = new HashMap<String, Object>();
- public StubInitialContext() throws NamingException {
- super(true);
- }
-
- @Override
- public void bind(String name, Object obj) throws NamingException {
- bindings.put(name, obj);
- }
+ public StubInitialContext() throws NamingException {
+ super(true);
+ }
- @Override
- public Object lookup(String name) throws NamingException {
- return bindings.get(name);
- }
-
- @Override
- public Object lookup(Name name) throws NamingException {
- return super.lookup(name.toString());
- }
+ @Override
+ public void bind(String name, Object obj) throws NamingException {
+ bindings.put(name, obj);
+ }
+
+ @Override
+ public Object lookup(String name) throws NamingException {
+ return bindings.get(name);
+ }
+
+ @Override
+ public Object lookup(Name name) throws NamingException {
+ return super.lookup(name.toString());
+ }
}
*/
public class StubInitialContextFactory implements InitialContextFactory {
- private static Context context;
-
- private static void initialize() {
- try {
- context = new StubInitialContext();
- } catch (NamingException e) { // can't happen.
- throw new RuntimeException(e);
- }
- }
-
- /**
- * This method must be called to register this initial context factory as
- * the default implementation for JNDI.
- *
- * @throws Exception
- */
- public static void register() {
- // sets up the InitialContextFactoryForTest as default factory.
- System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
- StubInitialContextFactory.class.getName());
- if (context == null) {
- initialize();
- }
- }
-
- /**
- * Unregisters the initial context factory
- */
- public static void unregister() {
- System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "");
- context = null;
- }
-
- public Context getInitialContext(Hashtable<?, ?> environment)
- throws NamingException {
- return context;
- }
+ private static Context context;
+
+ private static void initialize() {
+ try {
+ context = new StubInitialContext();
+ } catch (NamingException e) { // can't happen.
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * This method must be called to register this initial context factory as
+ * the default implementation for JNDI.
+ *
+ * @throws Exception
+ */
+ public static void register() {
+ // sets up the InitialContextFactoryForTest as default factory.
+ System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
+ StubInitialContextFactory.class.getName());
+ if (context == null) {
+ initialize();
+ }
+ }
+
+ /**
+ * Unregisters the initial context factory
+ */
+ public static void unregister() {
+ System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "");
+ context = null;
+ }
+
+ public Context getInitialContext(Hashtable<?, ?> environment)
+ throws NamingException {
+ return context;
+ }
}
import org.apache.commons.pool.impl.GenericObjectPool;
public abstract class AbstractDatabase implements Database {
- private static final int CONNECTION_POOL_SIZE = 16;
+ private static final int CONNECTION_POOL_SIZE = 16;
- private DataSource itsDataSource;
-
- private boolean started;
-
- protected AbstractDatabase() {
- started = false;
- }
-
- protected abstract void doStart();
-
- protected abstract void doStop();
-
- /**
- * This method must be called from the start method.
- */
- protected final void createDataSource() {
- GenericObjectPool connectionPool = new GenericObjectPool(null);
- connectionPool.setMaxActive(CONNECTION_POOL_SIZE);
- ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(getJdbcUrl(), getUsername(), getPassword());
- // The following line must be kept in although it does not appear to be used, the constructor regsiters the
- // constructed object at the connection pool.
- PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
- itsDataSource = new PoolingDataSource(connectionPool);
- }
-
-
- /// BELOW THIS LINE IS NOT OF INTEREST TO SUBCLASSES.
-
- public final DataSource start() {
- if ( started ) {
- throw new RuntimeException("Database already started");
- }
- started = true;
- doStart();
- return getDatasource();
- }
-
- public final void stop() {
- if ( ! started ) {
- return; // nothing to do.
- }
- started = false;
- doStop();
- }
+ private DataSource itsDataSource;
- private final DataSource getDatasource() {
- if ( !started) {
- throw new RuntimeException("Database is not started!");
- }
- return itsDataSource;
- }
-
- protected String getProperty(String aName) {
- String value = System.getProperty(aName);
- if ( value != null ) {
- return value;
- }
- value = System.getenv(aName);
- if ( value != null ) {
- return value;
- }
- throw new RuntimeException("This class expects the '" + aName + "' property to be set");
- }
+ private boolean started;
+
+ protected AbstractDatabase() {
+ started = false;
+ }
+
+ protected abstract void doStart();
+
+ protected abstract void doStop();
+
+ /**
+ * This method must be called from the start method.
+ */
+ protected final void createDataSource() {
+ GenericObjectPool connectionPool = new GenericObjectPool(null);
+ connectionPool.setMaxActive(CONNECTION_POOL_SIZE);
+ ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
+ getJdbcUrl(), getUsername(), getPassword());
+ // The following line must be kept in although it does not appear to be
+ // used, the constructor regsiters the
+ // constructed object at the connection pool.
+ PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
+ connectionFactory, connectionPool, null, null, false, true);
+ itsDataSource = new PoolingDataSource(connectionPool);
+ }
+
+ // / BELOW THIS LINE IS NOT OF INTEREST TO SUBCLASSES.
+
+ public final DataSource start() {
+ if (started) {
+ throw new RuntimeException("Database already started");
+ }
+ started = true;
+ doStart();
+ return getDatasource();
+ }
+
+ public final void stop() {
+ if (!started) {
+ return; // nothing to do.
+ }
+ started = false;
+ doStop();
+ }
+
+ private final DataSource getDatasource() {
+ if (!started) {
+ throw new RuntimeException("Database is not started!");
+ }
+ return itsDataSource;
+ }
+
+ protected String getProperty(String aName) {
+ String value = System.getProperty(aName);
+ if (value != null) {
+ return value;
+ }
+ value = System.getenv(aName);
+ if (value != null) {
+ return value;
+ }
+ throw new RuntimeException("This class expects the '" + aName +
+ "' property to be set");
+ }
}
public abstract class AbstractDatabaseProvider implements DatabaseProvider {
- protected abstract List<String> getCapabilities();
+ protected abstract List<String> getCapabilities();
- public final boolean supportsCapabilities(String[] aCapabilities) {
- for (String capability: aCapabilities) {
- if ( !getCapabilities().contains(capability)) {
- return false;
- }
- }
- return true;
- }
+ public final boolean supportsCapabilities(String[] aCapabilities) {
+ for (String capability : aCapabilities) {
+ if (!getCapabilities().contains(capability)) {
+ return false;
+ }
+ }
+ return true;
+ }
}
import org.dbunit.dataset.filter.ITableFilterSimple;
public class CompositeJpaCustomizer implements JpaCustomizer {
-
+
private List<JpaCustomizer> customizers;
- private CompositeJpaTables tables;
-
- public CompositeJpaCustomizer(List<JpaCustomizer> aCustomizers) {
+ private CompositeJpaTables tables;
+
+ public CompositeJpaCustomizer(List<JpaCustomizer> aCustomizers) {
customizers = aCustomizers;
tables = new CompositeJpaTables();
- for (JpaCustomizer customizer: customizers) {
+ for (JpaCustomizer customizer : customizers) {
tables.add(customizer.getJpaTables());
- }
+ }
}
-
+
@Override
- public void customize(PersistenceUnitDescription aPersistenceUnit, Map<String, String> aJpaProperties) {
- for (JpaCustomizer customizer: customizers) {
- customizer.customize(aPersistenceUnit, aJpaProperties);
+ public void customize(PersistenceUnitDescription aPersistenceUnit,
+ Map<String, String> aJpaProperties) {
+ for (JpaCustomizer customizer : customizers) {
+ customizer.customize(aPersistenceUnit, aJpaProperties);
}
}
@Override
public ITableFilterSimple getJpaTables() {
- return tables;
+ return tables;
}
}
import org.dbunit.dataset.filter.ITableFilterSimple;
public class CompositeJpaTables implements ITableFilterSimple {
-
- private List<ITableFilterSimple> tables;
-
- public CompositeJpaTables() {
+
+ private List<ITableFilterSimple> tables;
+
+ public CompositeJpaTables() {
tables = new ArrayList<ITableFilterSimple>();
}
-
- public void add(ITableFilterSimple aFilter) {
+
+ public void add(ITableFilterSimple aFilter) {
tables.add(aFilter);
}
@Override
public boolean accept(String aTableName) throws DataSetException {
- for (ITableFilterSimple filter: tables) {
- if (filter.accept(aTableName)) {
- return true;
+ for (ITableFilterSimple filter : tables) {
+ if (filter.accept(aTableName)) {
+ return true;
}
}
- return false;
+ return false;
}
}
* @author Erik Brakkee
*/
public interface Database {
-
+
/**
* Starts a database. This call should not block and return as soon as the
* database has been started.
*/
DataSource start();
-
+
/**
* Gets the Jdbc Url to connect to this database.
*
/**
* DatabaseBuilder is used from unit test to obtain a reference to a database
* from unit test. This database is either an inmemory database or represents an
- * external database. Purpose of this utility is to make test code independent of the
- * particular database used and specifically to be able to run database tests without
- * any configuration at all (using an inmemory database).
+ * external database. Purpose of this utility is to make test code independent
+ * of the particular database used and specifically to be able to run database
+ * tests without any configuration at all (using an inmemory database).
*
* The type of database to use can be overridden by specifying either a system
* property or an environment variable ({@link #DB_CAPABILITIES_PROP}) that
* provides its own capabilities (see {@link DatabaseProvider} implementations}.
*
*
- * There are currently two database types available:
+ * There are currently two database types available:
* <ul>
- * <li> Derby: AN inmemory derby. Provided by {@link DerbyDatabaseProvider}. This is the default.
- * </li>
- * <li> External: An arbitrary external database configured using system properties or environment variables
- * in the usual way using a JDBC URL, username, and password.
- * </li>
+ * <li>Derby: AN inmemory derby. Provided by {@link DerbyDatabaseProvider}. This
+ * is the default.</li>
+ * <li>External: An arbitrary external database configured using system
+ * properties or environment variables in the usual way using a JDBC URL,
+ * username, and password.</li>
* </ul>
*
- * The <code>DatabaseBuilder</code> uses the {@link ServiceLoader} mechanism to find implementations
- * of {@link DatabaseProvider} on the classpath. In the {@link #getDatabase(String...)} method a number of
- * capabilities are passed. The database providers are then searched in (arbitrary) order and the first one that
- * has all required capabilities is returned.
+ * The <code>DatabaseBuilder</code> uses the {@link ServiceLoader} mechanism to
+ * find implementations of {@link DatabaseProvider} on the classpath. In the
+ * {@link #getDatabase(String...)} method a number of capabilities are passed.
+ * The database providers are then searched in (arbitrary) order and the first
+ * one that has all required capabilities is returned.
*
- * {@link #getSupportedDatabases()} gives a list of all available databases.
+ * {@link #getSupportedDatabases()} gives a list of all available databases.
*/
public class DatabaseBuilder {
- private static final Logger LOGGER = Logger.getLogger(DatabaseBuilder.class
- .getName());
+ private static final Logger LOGGER = Logger.getLogger(DatabaseBuilder.class
+ .getName());
- /**
- * Environmment variable by which capabilities of the requested database can
- * be defined
- */
- private static final String DB_CAPABILITIES_PROP = "TEST_DB_CAPABILITIES";
+ /**
+ * Environmment variable by which capabilities of the requested database can
+ * be defined
+ */
+ private static final String DB_CAPABILITIES_PROP = "TEST_DB_CAPABILITIES";
- private static ServiceLoader<DatabaseProvider> LOADER = null;
+ private static ServiceLoader<DatabaseProvider> LOADER = null;
- private DatabaseBuilder() {
- // Empty.
- }
+ private DatabaseBuilder() {
+ // Empty.
+ }
- private static String[] parseCapabilities(String aValue) {
- return aValue.split(",");
- }
+ private static String[] parseCapabilities(String aValue) {
+ return aValue.split(",");
+ }
- /**
- * Gets the first database that has all required capabilities.
- * @param aCapabilities Capabilities.
- * @return Database to use.
- */
- public static Database getDatabase(String... aCapabilities) {
- if (aCapabilities.length == 0) {
- LOGGER.info("Examining database capabilities");
- LOGGER.info(" Checking system property " + DB_CAPABILITIES_PROP);
- String capabilities = System.getProperty(DB_CAPABILITIES_PROP);
- if (capabilities != null) {
- aCapabilities = parseCapabilities(capabilities);
- } else {
- LOGGER.info(" Checking environment variable "
- + DB_CAPABILITIES_PROP);
- capabilities = System.getenv(DB_CAPABILITIES_PROP);
- if (capabilities != null) {
- aCapabilities = parseCapabilities(capabilities);
- } else {
- LOGGER.info(" Using default capabilities");
- aCapabilities = new String[] { DatabaseProvider.CAPABILITY_IN_MEMORY };
- }
- }
- LOGGER.info("Using capabilities: " + aCapabilities);
- }
- synchronized (DatabaseBuilder.class) {
- initLoader();
- for (DatabaseProvider db : LOADER) {
- if (db.supportsCapabilities(aCapabilities)) {
- return db.create();
- }
- }
- }
- throw new RuntimeException(
- "No database found that satisfies capabilities: "
- + Arrays.asList(aCapabilities));
- }
+ /**
+ * Gets the first database that has all required capabilities.
+ *
+ * @param aCapabilities
+ * Capabilities.
+ * @return Database to use.
+ */
+ public static Database getDatabase(String... aCapabilities) {
+ if (aCapabilities.length == 0) {
+ LOGGER.info("Examining database capabilities");
+ LOGGER.info(" Checking system property " + DB_CAPABILITIES_PROP);
+ String capabilities = System.getProperty(DB_CAPABILITIES_PROP);
+ if (capabilities != null) {
+ aCapabilities = parseCapabilities(capabilities);
+ } else {
+ LOGGER.info(" Checking environment variable " +
+ DB_CAPABILITIES_PROP);
+ capabilities = System.getenv(DB_CAPABILITIES_PROP);
+ if (capabilities != null) {
+ aCapabilities = parseCapabilities(capabilities);
+ } else {
+ LOGGER.info(" Using default capabilities");
+ aCapabilities = new String[] { DatabaseProvider.CAPABILITY_IN_MEMORY };
+ }
+ }
+ LOGGER.info("Using capabilities: " + aCapabilities);
+ }
+ synchronized (DatabaseBuilder.class) {
+ initLoader();
+ for (DatabaseProvider db : LOADER) {
+ if (db.supportsCapabilities(aCapabilities)) {
+ return db.create();
+ }
+ }
+ }
+ throw new RuntimeException(
+ "No database found that satisfies capabilities: " +
+ Arrays.asList(aCapabilities));
+ }
- /**
- * Gets a list of available databases.
- * @return List of databases.
- */
- public static List<DatabaseDescription> getSupportedDatabases() {
- initLoader();
- List<DatabaseDescription> descriptions = new ArrayList<DatabaseDescription>();
- for (DatabaseProvider db : LOADER) {
- descriptions.add(db.getDescription());
- }
- return descriptions;
- }
+ /**
+ * Gets a list of available databases.
+ *
+ * @return List of databases.
+ */
+ public static List<DatabaseDescription> getSupportedDatabases() {
+ initLoader();
+ List<DatabaseDescription> descriptions = new ArrayList<DatabaseDescription>();
+ for (DatabaseProvider db : LOADER) {
+ descriptions.add(db.getDescription());
+ }
+ return descriptions;
+ }
- private static void initLoader() {
- if (LOADER == null) {
- LOADER = ServiceLoader.load(DatabaseProvider.class);
- }
- }
+ private static void initLoader() {
+ if (LOADER == null) {
+ LOADER = ServiceLoader.load(DatabaseProvider.class);
+ }
+ }
}
package org.wamblee.support.persistence;
/**
- * Description of a specific database.
+ * Description of a specific database.
*/
public class DatabaseDescription {
- private String[] itsCapabilities;
- private String itsDatabase;
- private String itsOther;
-
- /**
- * Constructs the description.
- * @param aCapabilities List of all capabilities.
- * @param aDatabase Database.
- * @param aOther Other information.
- */
- public DatabaseDescription(String[] aCapabilities, String aDatabase, String aOther) {
- itsCapabilities = aCapabilities;
- itsDatabase = aDatabase;
- itsOther = aOther;
- }
-
- @Override
- public String toString() {
- return "\n Database " + itsDatabase +
- "\n Capabilities: " + printCapabilities() +
- "\n Other info: " + itsOther;
- }
-
- private String printCapabilities() {
- String res = "";
- for (int i = 0; i < itsCapabilities.length; i++) {
- res += "" + itsCapabilities[i];
- if ( i < itsCapabilities.length -1 ) {
- res += ", ";
- }
- }
- return res;
- }
+ private String[] itsCapabilities;
+ private String itsDatabase;
+ private String itsOther;
+
+ /**
+ * Constructs the description.
+ *
+ * @param aCapabilities
+ * List of all capabilities.
+ * @param aDatabase
+ * Database.
+ * @param aOther
+ * Other information.
+ */
+ public DatabaseDescription(String[] aCapabilities, String aDatabase,
+ String aOther) {
+ itsCapabilities = aCapabilities;
+ itsDatabase = aDatabase;
+ itsOther = aOther;
+ }
+
+ @Override
+ public String toString() {
+ return "\n Database " + itsDatabase + "\n Capabilities: " +
+ printCapabilities() + "\n Other info: " + itsOther;
+ }
+
+ private String printCapabilities() {
+ String res = "";
+ for (int i = 0; i < itsCapabilities.length; i++) {
+ res += "" + itsCapabilities[i];
+ if (i < itsCapabilities.length - 1) {
+ res += ", ";
+ }
+ }
+ return res;
+ }
}
*/
public interface DatabaseProvider {
- /**
- * Capability that all databases that run inmemory have.
- */
- String CAPABILITY_IN_MEMORY = "INMEMORY";
+ /**
+ * Capability that all databases that run inmemory have.
+ */
+ String CAPABILITY_IN_MEMORY = "INMEMORY";
- /**
- * Capability that all databases that are external have.
- */
- String CAPABILITY_EXTERNAL = "EXTERNAL";
+ /**
+ * Capability that all databases that are external have.
+ */
+ String CAPABILITY_EXTERNAL = "EXTERNAL";
- /**
- * Determines if the database has all capabilities that are requested.
- * @param aCapabilities Capabilities it must ahve
- * @return True if it has all capabilities.
- */
- boolean supportsCapabilities(String[] aCapabilities);
+ /**
+ * Determines if the database has all capabilities that are requested.
+ *
+ * @param aCapabilities
+ * Capabilities it must ahve
+ * @return True if it has all capabilities.
+ */
+ boolean supportsCapabilities(String[] aCapabilities);
- /**
- * Gets the description for the database.
- * @return Description.
- */
- DatabaseDescription getDescription();
+ /**
+ * Gets the description for the database.
+ *
+ * @return Description.
+ */
+ DatabaseDescription getDescription();
- /**
- * Creates a database instance that represents a running instance of that database.
- * @return Database.
- */
- Database create();
+ /**
+ * Creates a database instance that represents a running instance of that
+ * database.
+ *
+ * @return Database.
+ */
+ Database create();
}
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.support.persistence;
-
/**
* This class is used for starting the database from ant.
*/
* <pre>
*
* DatabaseStarter <databaseClassName>
- *
+ *
* </pre>
*
* where the database class name must be the name of a concrete subclass of
*
* @param args
*/
- public static void main( String[] args ) throws Exception {
+ public static void main(String[] args) throws Exception {
String clazz = args[0];
try {
- new DatabaseStarter( Class.forName( clazz ) ).start( );
- } catch ( Exception e ) {
- e.printStackTrace( );
- System.out
- .println( "\nUsage: ant dbClass ");
+ new DatabaseStarter(Class.forName(clazz)).start();
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.out.println("\nUsage: ant dbClass ");
}
}
* Classname of the database class to use.
* @throws Exception
*/
- public DatabaseStarter( Class aClass ) throws Exception {
- if ( !Database.class.isAssignableFrom( aClass ) ) {
- throw new IllegalArgumentException( "Class '"
- + aClass.getName( )
- + "' is not a subclass of Database" );
+ public DatabaseStarter(Class aClass) throws Exception {
+ if (!Database.class.isAssignableFrom(aClass)) {
+ throw new IllegalArgumentException("Class '" + aClass.getName() +
+ "' is not a subclass of Database");
}
databaseClass = aClass;
}
*
* @throws Exception
*/
- public DatabaseStarter( ) throws Exception {
- this( DerbyDatabase.class );
+ public DatabaseStarter() throws Exception {
+ this(DerbyDatabase.class);
}
/**
*
* @throws Exception
*/
- public void start( ) throws Exception {
- Database lDatabase = (Database) databaseClass.newInstance( );
- lDatabase.start( );
- System.out.println( "Database has been started. " );
- System.out.println( );
- System.out.println("=======================================================");
- System.out.println( "Connection details:" );
- // System.out.println( " Driver class: "
- // + lDatabase.getDriverClassName( ) );
- System.out.println( " JDBC URL: "
- + lDatabase.getExternalJdbcUrl( ) );
- System.out.println( " username: '" + lDatabase.getUsername( )
- + "'" );
- System.out.println( " password: '" + lDatabase.getPassword( )
- + "'" );
- System.out.println( "Interrupt the program to stop the database." );
- System.out.println("=======================================================");
- System.out.println("You must now populate the database with a schema. Use 'ant help' for information.");
- for ( ;; ) {
- Thread.sleep( 1000 );
+ public void start() throws Exception {
+ Database lDatabase = (Database) databaseClass.newInstance();
+ lDatabase.start();
+ System.out.println("Database has been started. ");
+ System.out.println();
+ System.out
+ .println("=======================================================");
+ System.out.println("Connection details:");
+ // System.out.println( " Driver class: "
+ // + lDatabase.getDriverClassName( ) );
+ System.out.println(" JDBC URL: " + lDatabase.getExternalJdbcUrl());
+ System.out.println(" username: '" + lDatabase.getUsername() + "'");
+ System.out.println(" password: '" + lDatabase.getPassword() + "'");
+ System.out.println("Interrupt the program to stop the database.");
+ System.out
+ .println("=======================================================");
+ System.out
+ .println("You must now populate the database with a schema. Use 'ant help' for information.");
+ for (;;) {
+ Thread.sleep(1000);
}
}
}
*/
public class DatabaseUtils {
- public static interface TableSet {
- boolean contains(String aTableName);
- }
-
- public static interface JdbcUnitOfWork<T> {
- T execute(Connection aConnection) throws Exception;
- }
-
- public static interface TableSetOperation {
- void execute(String aTable) throws Exception;
- }
-
- private static final Logger LOG = Logger.getLogger(DatabaseUtils.class
- .getName());
-
- /**
- * Schema pattern.
- */
- private static final String SCHEMA_PATTERN = "%";
- private DataSource dataSource;
- private ITableFilterSimple tables;
-
-
- public DatabaseUtils(DataSource aDataSource, ITableFilterSimple aTables) {
- dataSource = aDataSource;
- tables = aTables;
- }
-
- public IDatabaseTester createDbTester() throws Exception {
- return createDbTester(getTableNames(tables));
- }
-
- public IDatabaseTester createDbTester(String[] aTables) throws Exception {
- IDatabaseTester dbtester = new DataSourceDatabaseTester(dataSource);
- dbtester.setDataSet(dbtester.getConnection().createDataSet(aTables));
- return dbtester;
- }
-
- public void cleanDatabase() throws Exception {
- cleanDatabase(tables);
- }
-
- public void executeOnTables(ITableFilterSimple aTables,
- final TableSetOperation aOperation) throws Exception {
- final String[] tables = getTableNames(aTables);
- executeInTransaction(new JdbcUnitOfWork<Void>() {
- public Void execute(Connection aConnection) throws Exception {
- for (int i = tables.length - 1; i >= 0; i--) {
- aOperation.execute(tables[i]);
- }
- return null;
- }
- });
- for (String table : tables) {
-
- }
- }
-
- public void cleanDatabase(ITableFilterSimple aSelection) throws Exception {
-
- final String[] tables = getTableNames(aSelection);
- executeInTransaction(new JdbcUnitOfWork<Void>() {
-
- public Void execute(Connection aConnection) throws Exception {
- IDatabaseConnection connection = new DatabaseConnection(
- aConnection);
- ITableFilter filter = new DatabaseSequenceFilter(connection,
- tables);
- IDataSet dataset = new FilteredDataSet(filter, connection
- .createDataSet(tables));
- DatabaseOperation.DELETE_ALL.execute(connection, dataset);
- return null;
- }
- });
-
- }
-
- public <T> T executeInTransaction(JdbcUnitOfWork<T> aCallback)
- throws Exception {
- Connection connection = dataSource.getConnection();
- try {
- T value = aCallback.execute(connection);
- connection.commit();
- return value;
- } finally {
- connection.close();
- }
- }
-
- public String[] getTableNames() throws Exception {
- return getTableNames(tables);
- }
-
- /**
- * @throws SQLException
- */
- public String[] getTableNames(ITableFilterSimple aSelection)
- throws Exception {
-
- List<String> result = new ArrayList<String>();
- LOG.fine("Getting database table names to clean (schema: '"
- + SCHEMA_PATTERN + "'");
-
- ResultSet tables = dataSource.getConnection().getMetaData().getTables(
- null, SCHEMA_PATTERN, "%", new String[] { "TABLE" });
- while (tables.next()) {
- String table = tables.getString("TABLE_NAME");
- if (aSelection.accept(table)) {
- result.add(table);
- }
- }
- return (String[]) result.toArray(new String[0]);
- }
-
- public void emptyTables() throws Exception {
- executeOnTables(tables, new TableSetOperation() {
- public void execute(String aTable) throws Exception {
- emptyTable(aTable);
- }
- });
- }
-
- /**
- * @return
- * @throws SQLException
- */
- public void emptyTables(final ITableFilterSimple aSelection)
- throws Exception {
- executeOnTables(aSelection, new TableSetOperation() {
- public void execute(String aTable) throws Exception {
- emptyTable(aTable);
- }
- });
- }
-
- /**
- * @return
- * @throws SQLException
- */
- public void emptyTable(String aTable) throws Exception {
- executeSql("delete from " + aTable);
- }
-
- public void dropTables() throws Exception {
- executeOnTables(tables, new TableSetOperation() {
-
- public void execute(String aTable) throws Exception {
- dropTable(aTable);
- }
- });
- }
-
-
- public void dropTables(ITableFilterSimple aTables) throws Exception {
- executeOnTables(aTables, new TableSetOperation() {
-
- public void execute(String aTable) throws Exception {
- dropTable(aTable);
- }
- });
- }
-
- /**
- * @return
- * @throws SQLException
- */
- public void dropTable(final String aTable) throws Exception {
- executeInTransaction(new JdbcUnitOfWork<Void>() {
- public Void execute(Connection aConnection) throws Exception {
- executeUpdate(aConnection, "drop table " + aTable);
- return null;
- }
- });
-
- }
-
- /**
- * Executes an SQL statement within a transaction.
- *
- * @param aSql
- * SQL statement.
- * @return Return code of the corresponding JDBC call.
- */
- public int executeSql(final String aSql) throws Exception {
- return executeSql(aSql, new Object[0]);
- }
-
- /**
- * Executes an SQL statement within a transaction. See
- * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
- * supported argument types.
- *
- * @param aSql
- * SQL statement.
- * @param aArg
- * Argument of the sql statement.
- * @return Return code of the corresponding JDBC call.
- */
- public int executeSql(final String aSql, final Object aArg)
- throws Exception {
- return executeSql(aSql, new Object[] { aArg });
- }
-
- /**
- * Executes an sql statement. See
- * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
- * supported argument types.
- *
- * @param aSql
- * SQL query to execute.
- * @param aArgs
- * Arguments.
- * @return Number of rows updated.
- */
- public int executeSql(final String aSql, final Object[] aArgs)
- throws Exception {
- return executeInTransaction(new JdbcUnitOfWork<Integer>() {
- public Integer execute(Connection aConnection) throws Exception {
- PreparedStatement stmt = aConnection.prepareStatement(aSql);
- setPreparedParams(aArgs, stmt);
- return stmt.executeUpdate();
- }
- });
- }
-
- /**
- * Executes an SQL query.
- *
- * @param aSql
- * Query to execute.
- * @return Result set.
- */
- public ResultSet executeQuery(Connection aConnection, String aSql) {
- return executeQuery(aConnection, aSql, new Object[0]);
- }
-
- /**
- * Executes a query with a single argument. See
- * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
- * supported argument types.
- *
- * @param aSql
- * Query.
- * @param aArg
- * Argument.
- * @return Result set.
- */
- public ResultSet executeQuery(Connection aConnection, String aSql,
- Object aArg) {
- return executeQuery(aConnection, aSql, new Object[] { aArg });
- }
-
- /**
- * Executes a query. See
- * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
- * supported argument types.
- *
- * @param aSql
- * Sql query.
- * @param aArgs
- * Arguments to the query.
- * @return Result set.
- */
- public ResultSet executeQuery(Connection aConnection, final String aSql,
- final Object[] aArgs) {
- try {
- PreparedStatement statement = aConnection.prepareStatement(aSql);
- setPreparedParams(aArgs, statement);
-
- return statement.executeQuery();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public int executeUpdate(Connection aConnection, final String aSql,
- final Object... aArgs) {
- try {
- PreparedStatement statement = aConnection.prepareStatement(aSql);
- setPreparedParams(aArgs, statement);
-
- return statement.executeUpdate();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Sets the values of a prepared statement. See
- * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
- * supported argument types.
- *
- * @param aArgs
- * Arguments to the prepared statement.
- * @param aStatement
- * Prepared statement
- * @throws SQLException
- */
- private void setPreparedParams(final Object[] aArgs,
- PreparedStatement aStatement) throws SQLException {
- for (int i = 1; i <= aArgs.length; i++) {
- setPreparedParam(i, aStatement, aArgs[i - 1]);
- }
- }
-
- /**
- * Sets a prepared statement parameter.
- *
- * @param aIndex
- * Index of the parameter.
- * @param aStatement
- * Prepared statement.
- * @param aObject
- * Value Must be of type Integer, Long, or String.
- * @throws SQLException
- */
- private void setPreparedParam(int aIndex, PreparedStatement aStatement,
- Object aObject) throws SQLException {
- if (aObject instanceof Integer) {
- aStatement.setInt(aIndex, ((Integer) aObject).intValue());
- } else if (aObject instanceof Long) {
- aStatement.setLong(aIndex, ((Integer) aObject).longValue());
- } else if (aObject instanceof String) {
- aStatement.setString(aIndex, (String) aObject);
- } else {
- TestCase.fail("Unsupported object type for prepared statement: "
- + aObject.getClass() + " value: " + aObject
- + " statement: " + aStatement);
- }
- }
-
- /**
- * @return
- * @throws SQLException
- */
- public int getTableSize(final String aTable) throws Exception {
- return executeInTransaction(new JdbcUnitOfWork<Integer>() {
- public Integer execute(Connection aConnection) throws Exception {
- ResultSet resultSet = executeQuery(aConnection,
- "select count(*) from " + aTable);
- resultSet.next();
- return resultSet.getInt(1);
- }
- });
-
- }
-
- public int countResultSet(ResultSet aResultSet) throws SQLException {
- int count = 0;
-
- while (aResultSet.next()) {
- count++;
- }
-
- return count;
- }
+ public static interface TableSet {
+ boolean contains(String aTableName);
+ }
+
+ public static interface JdbcUnitOfWork<T> {
+ T execute(Connection aConnection) throws Exception;
+ }
+
+ public static interface TableSetOperation {
+ void execute(String aTable) throws Exception;
+ }
+
+ private static final Logger LOG = Logger.getLogger(DatabaseUtils.class
+ .getName());
+
+ /**
+ * Schema pattern.
+ */
+ private static final String SCHEMA_PATTERN = "%";
+ private DataSource dataSource;
+ private ITableFilterSimple tables;
+
+ public DatabaseUtils(DataSource aDataSource, ITableFilterSimple aTables) {
+ dataSource = aDataSource;
+ tables = aTables;
+ }
+
+ public IDatabaseTester createDbTester() throws Exception {
+ return createDbTester(getTableNames(tables));
+ }
+
+ public IDatabaseTester createDbTester(String[] aTables) throws Exception {
+ IDatabaseTester dbtester = new DataSourceDatabaseTester(dataSource);
+ dbtester.setDataSet(dbtester.getConnection().createDataSet(aTables));
+ return dbtester;
+ }
+
+ public void cleanDatabase() throws Exception {
+ cleanDatabase(tables);
+ }
+
+ public void executeOnTables(ITableFilterSimple aTables,
+ final TableSetOperation aOperation) throws Exception {
+ final String[] tables = getTableNames(aTables);
+ executeInTransaction(new JdbcUnitOfWork<Void>() {
+ public Void execute(Connection aConnection) throws Exception {
+ for (int i = tables.length - 1; i >= 0; i--) {
+ aOperation.execute(tables[i]);
+ }
+ return null;
+ }
+ });
+ for (String table : tables) {
+
+ }
+ }
+
+ public void cleanDatabase(ITableFilterSimple aSelection) throws Exception {
+
+ final String[] tables = getTableNames(aSelection);
+ executeInTransaction(new JdbcUnitOfWork<Void>() {
+
+ public Void execute(Connection aConnection) throws Exception {
+ IDatabaseConnection connection = new DatabaseConnection(
+ aConnection);
+ ITableFilter filter = new DatabaseSequenceFilter(connection,
+ tables);
+ IDataSet dataset = new FilteredDataSet(filter, connection
+ .createDataSet(tables));
+ DatabaseOperation.DELETE_ALL.execute(connection, dataset);
+ return null;
+ }
+ });
+
+ }
+
+ public <T> T executeInTransaction(JdbcUnitOfWork<T> aCallback)
+ throws Exception {
+ Connection connection = dataSource.getConnection();
+ try {
+ T value = aCallback.execute(connection);
+ connection.commit();
+ return value;
+ } finally {
+ connection.close();
+ }
+ }
+
+ public String[] getTableNames() throws Exception {
+ return getTableNames(tables);
+ }
+
+ /**
+ * @throws SQLException
+ */
+ public String[] getTableNames(ITableFilterSimple aSelection)
+ throws Exception {
+
+ List<String> result = new ArrayList<String>();
+ LOG.fine("Getting database table names to clean (schema: '" +
+ SCHEMA_PATTERN + "'");
+
+ ResultSet tables = dataSource.getConnection().getMetaData().getTables(
+ null, SCHEMA_PATTERN, "%", new String[] { "TABLE" });
+ while (tables.next()) {
+ String table = tables.getString("TABLE_NAME");
+ if (aSelection.accept(table)) {
+ result.add(table);
+ }
+ }
+ return (String[]) result.toArray(new String[0]);
+ }
+
+ public void emptyTables() throws Exception {
+ executeOnTables(tables, new TableSetOperation() {
+ public void execute(String aTable) throws Exception {
+ emptyTable(aTable);
+ }
+ });
+ }
+
+ /**
+ * @return
+ * @throws SQLException
+ */
+ public void emptyTables(final ITableFilterSimple aSelection)
+ throws Exception {
+ executeOnTables(aSelection, new TableSetOperation() {
+ public void execute(String aTable) throws Exception {
+ emptyTable(aTable);
+ }
+ });
+ }
+
+ /**
+ * @return
+ * @throws SQLException
+ */
+ public void emptyTable(String aTable) throws Exception {
+ executeSql("delete from " + aTable);
+ }
+
+ public void dropTables() throws Exception {
+ executeOnTables(tables, new TableSetOperation() {
+
+ public void execute(String aTable) throws Exception {
+ dropTable(aTable);
+ }
+ });
+ }
+
+ public void dropTables(ITableFilterSimple aTables) throws Exception {
+ executeOnTables(aTables, new TableSetOperation() {
+
+ public void execute(String aTable) throws Exception {
+ dropTable(aTable);
+ }
+ });
+ }
+
+ /**
+ * @return
+ * @throws SQLException
+ */
+ public void dropTable(final String aTable) throws Exception {
+ executeInTransaction(new JdbcUnitOfWork<Void>() {
+ public Void execute(Connection aConnection) throws Exception {
+ executeUpdate(aConnection, "drop table " + aTable);
+ return null;
+ }
+ });
+
+ }
+
+ /**
+ * Executes an SQL statement within a transaction.
+ *
+ * @param aSql
+ * SQL statement.
+ * @return Return code of the corresponding JDBC call.
+ */
+ public int executeSql(final String aSql) throws Exception {
+ return executeSql(aSql, new Object[0]);
+ }
+
+ /**
+ * Executes an SQL statement within a transaction. See
+ * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * supported argument types.
+ *
+ * @param aSql
+ * SQL statement.
+ * @param aArg
+ * Argument of the sql statement.
+ * @return Return code of the corresponding JDBC call.
+ */
+ public int executeSql(final String aSql, final Object aArg)
+ throws Exception {
+ return executeSql(aSql, new Object[] { aArg });
+ }
+
+ /**
+ * Executes an sql statement. See
+ * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * supported argument types.
+ *
+ * @param aSql
+ * SQL query to execute.
+ * @param aArgs
+ * Arguments.
+ * @return Number of rows updated.
+ */
+ public int executeSql(final String aSql, final Object[] aArgs)
+ throws Exception {
+ return executeInTransaction(new JdbcUnitOfWork<Integer>() {
+ public Integer execute(Connection aConnection) throws Exception {
+ PreparedStatement stmt = aConnection.prepareStatement(aSql);
+ setPreparedParams(aArgs, stmt);
+ return stmt.executeUpdate();
+ }
+ });
+ }
+
+ /**
+ * Executes an SQL query.
+ *
+ * @param aSql
+ * Query to execute.
+ * @return Result set.
+ */
+ public ResultSet executeQuery(Connection aConnection, String aSql) {
+ return executeQuery(aConnection, aSql, new Object[0]);
+ }
+
+ /**
+ * Executes a query with a single argument. See
+ * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * supported argument types.
+ *
+ * @param aSql
+ * Query.
+ * @param aArg
+ * Argument.
+ * @return Result set.
+ */
+ public ResultSet executeQuery(Connection aConnection, String aSql,
+ Object aArg) {
+ return executeQuery(aConnection, aSql, new Object[] { aArg });
+ }
+
+ /**
+ * Executes a query. See
+ * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * supported argument types.
+ *
+ * @param aSql
+ * Sql query.
+ * @param aArgs
+ * Arguments to the query.
+ * @return Result set.
+ */
+ public ResultSet executeQuery(Connection aConnection, final String aSql,
+ final Object[] aArgs) {
+ try {
+ PreparedStatement statement = aConnection.prepareStatement(aSql);
+ setPreparedParams(aArgs, statement);
+
+ return statement.executeQuery();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public int executeUpdate(Connection aConnection, final String aSql,
+ final Object... aArgs) {
+ try {
+ PreparedStatement statement = aConnection.prepareStatement(aSql);
+ setPreparedParams(aArgs, statement);
+
+ return statement.executeUpdate();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Sets the values of a prepared statement. See
+ * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * supported argument types.
+ *
+ * @param aArgs
+ * Arguments to the prepared statement.
+ * @param aStatement
+ * Prepared statement
+ * @throws SQLException
+ */
+ private void setPreparedParams(final Object[] aArgs,
+ PreparedStatement aStatement) throws SQLException {
+ for (int i = 1; i <= aArgs.length; i++) {
+ setPreparedParam(i, aStatement, aArgs[i - 1]);
+ }
+ }
+
+ /**
+ * Sets a prepared statement parameter.
+ *
+ * @param aIndex
+ * Index of the parameter.
+ * @param aStatement
+ * Prepared statement.
+ * @param aObject
+ * Value Must be of type Integer, Long, or String.
+ * @throws SQLException
+ */
+ private void setPreparedParam(int aIndex, PreparedStatement aStatement,
+ Object aObject) throws SQLException {
+ if (aObject instanceof Integer) {
+ aStatement.setInt(aIndex, ((Integer) aObject).intValue());
+ } else if (aObject instanceof Long) {
+ aStatement.setLong(aIndex, ((Integer) aObject).longValue());
+ } else if (aObject instanceof String) {
+ aStatement.setString(aIndex, (String) aObject);
+ } else {
+ TestCase.fail("Unsupported object type for prepared statement: " +
+ aObject.getClass() + " value: " + aObject + " statement: " +
+ aStatement);
+ }
+ }
+
+ /**
+ * @return
+ * @throws SQLException
+ */
+ public int getTableSize(final String aTable) throws Exception {
+ return executeInTransaction(new JdbcUnitOfWork<Integer>() {
+ public Integer execute(Connection aConnection) throws Exception {
+ ResultSet resultSet = executeQuery(aConnection,
+ "select count(*) from " + aTable);
+ resultSet.next();
+ return resultSet.getInt(1);
+ }
+ });
+
+ }
+
+ public int countResultSet(ResultSet aResultSet) throws SQLException {
+ int count = 0;
+
+ while (aResultSet.next()) {
+ count++;
+ }
+
+ return count;
+ }
}
*/
public class DerbyDatabase extends AbstractDatabase {
- /**
- * Logger.
- */
- private static final Logger LOGGER = Logger.getLogger(DerbyDatabase.class
- .getName());
-
- /**
- * Database user name.
- */
- private static final String USERNAME = "sa";
-
- /**
- * Database password.
- */
- private static final String PASSWORD = "123";
- /**
- * Poll interval for the checking the server status.
- */
- private static final int POLL_INTERVAL = 100;
-
- /**
- * Maximum time to wait until the server has started or stopped.
- */
- private static final int MAX_WAIT_TIME = 10000;
-
- /**
- * Database name to use.
- */
- private static final String DATABASE_NAME = "testdb";
-
- /**
- * Path on the file system where derby files are stored.
- */
- private static final String DATABASE_PATH = "target/db/persistence/derby";
-
- /**
- * Derby property required to set the file system path
- * {@link #DATABASE_PATH}.
- */
- private static final String SYSTEM_PATH_PROPERTY = "derby.system.home";
-
-
- private boolean inmemory;
-
-
- /**
- * Constructs derby database class to allow creation of derby database
- * instances.
- */
- public DerbyDatabase() {
- inmemory = true;
- }
-
- public DerbyDatabase(boolean aInMemoryFlag) {
- inmemory = aInMemoryFlag;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.wamblee.persistence.Database#start()
- */
- public void doStart() {
- try {
- // just in case a previous run was killed without the
- // cleanup
- cleanPersistentStorage();
-
- if (!inmemory) {
- // set database path.
- Properties lProperties = System.getProperties();
- lProperties.put(SYSTEM_PATH_PROPERTY, DATABASE_PATH);
- }
-
- Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
-
- runDatabase();
-
- waitUntilStartedOrStopped(true);
-
- // Force creation of the database.
- Connection lConnection = createConnection();
- lConnection.close();
-
- LOGGER.info("Database started: \n URL = " + getExternalJdbcUrl() + "\n user = " + getUsername() + "\n password = "
- + getPassword());
-
- createDataSource();
-
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public void run() {
- if (isStarted()) {
- LOGGER.warning("Shutting down db");
- DerbyDatabase.this.stop();
- }
- }
- });
- } catch (Exception e) {
- throw new RuntimeException("Problem starting database", e);
- }
- }
-
- /**
- * Waits until the database server has started or stopped.
- *
- * @param aStarted
- * If true, waits until the server is up, if false, waits until
- * the server is down.
- * @throws InterruptedException
- */
- private void waitUntilStartedOrStopped(boolean aStarted)
- throws InterruptedException {
- long lWaited = 0;
-
- while (aStarted != isStarted()) {
- Thread.sleep(POLL_INTERVAL);
- lWaited += POLL_INTERVAL;
-
- if (lWaited > MAX_WAIT_TIME) {
- throw new RuntimeException(
- "Derby database did not start within " + MAX_WAIT_TIME
- + "ms");
- }
- }
- }
-
- /**
- * Checks if the database server has started or not.
- *
- * @return True if started, false otherwise.
- */
- private boolean isStarted() {
- try {
- getControl().ping();
-
- return true;
- } catch (Exception e) {
- return false;
- }
- }
-
- /**
- * Gets the controller for the database server.
- *
- * @return Controller.
- * @throws Exception
- */
- private NetworkServerControl getControl() throws Exception {
- return new NetworkServerControl();
- }
-
- /**
- * Runs the database.
- *
- */
- private void runDatabase() {
- try {
- getControl().start(new PrintWriter(System.out));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.wamblee.persistence.Database#getJdbcUrl()
- */
- public String getJdbcUrl() {
- return getBaseJdbcUrl()
- + ";create=true;retrieveMessagesFromServerOnGetMessage=true;";
- }
-
- private String getBaseJdbcUrl() {
- return (inmemory ? "jdbc:derby:memory:": "jdbc:derby:") + DATABASE_NAME;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.wamblee.persistence.Database#getExternalJdbcUrl()
- */
- public String getExternalJdbcUrl() {
- return "jdbc:derby://localhost:1527/" + (inmemory ? "memory:" : "") + DATABASE_NAME;
- }
-
- /**
- * Shuts down the derby database and cleans up all created files.
- *
- */
- private void shutdownDerby() {
- try {
- DriverManager.getConnection("jdbc:derby:;shutdown=true");
- throw new RuntimeException("Derby did not shutdown, "
- + " should always throw exception at shutdown");
- } catch (Exception e) {
- LOGGER.info("Derby has been shut down.");
- }
- }
-
- /**
- * Gets the user name.
- */
- public String getUsername() {
- return USERNAME;
- }
-
- /**
- * Gets the password.
- *
- * @return
- */
- public String getPassword() {
- return PASSWORD;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.wamblee.persistence.Database#createConnection()
- */
- public Connection createConnection() throws SQLException {
- Connection c = DriverManager.getConnection(getJdbcUrl(), getUsername(),
- getPassword());
-
- return c;
- }
-
-
- /**
- * Stops the derby database and cleans up all derby files.
- */
- public void doStop() {
- try {
- // shutdown network server.
- getControl().shutdown();
- waitUntilStartedOrStopped(false);
-
- // shutdown inmemory access.
- shutdownDerby();
- cleanPersistentStorage();
- } catch (Exception e) {
- LOGGER.log(Level.WARNING, "Problem stopping database", e);
- }
- }
-
- /**
- * Cleans up persistent storage of Derby.
- */
- private void cleanPersistentStorage() {
- File lFile = new File(DATABASE_PATH);
-
- if (lFile.isFile()) {
- TestCase.fail("A regular file by the name " + DATABASE_PATH
- + " exists, clean this up first");
- }
-
- if (!lFile.isDirectory()) {
- return; // no-op already cleanup up.
- }
- FileSystemUtils.deleteDirRecursively(DATABASE_PATH);
- }
+ /**
+ * Logger.
+ */
+ private static final Logger LOGGER = Logger.getLogger(DerbyDatabase.class
+ .getName());
+
+ /**
+ * Database user name.
+ */
+ private static final String USERNAME = "sa";
+
+ /**
+ * Database password.
+ */
+ private static final String PASSWORD = "123";
+ /**
+ * Poll interval for the checking the server status.
+ */
+ private static final int POLL_INTERVAL = 100;
+
+ /**
+ * Maximum time to wait until the server has started or stopped.
+ */
+ private static final int MAX_WAIT_TIME = 10000;
+
+ /**
+ * Database name to use.
+ */
+ private static final String DATABASE_NAME = "testdb";
+
+ /**
+ * Path on the file system where derby files are stored.
+ */
+ private static final String DATABASE_PATH = "target/db/persistence/derby";
+
+ /**
+ * Derby property required to set the file system path
+ * {@link #DATABASE_PATH}.
+ */
+ private static final String SYSTEM_PATH_PROPERTY = "derby.system.home";
+
+ private boolean inmemory;
+
+ /**
+ * Constructs derby database class to allow creation of derby database
+ * instances.
+ */
+ public DerbyDatabase() {
+ inmemory = true;
+ }
+
+ public DerbyDatabase(boolean aInMemoryFlag) {
+ inmemory = aInMemoryFlag;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.wamblee.persistence.Database#start()
+ */
+ public void doStart() {
+ try {
+ // just in case a previous run was killed without the
+ // cleanup
+ cleanPersistentStorage();
+
+ if (!inmemory) {
+ // set database path.
+ Properties lProperties = System.getProperties();
+ lProperties.put(SYSTEM_PATH_PROPERTY, DATABASE_PATH);
+ }
+
+ Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
+
+ runDatabase();
+
+ waitUntilStartedOrStopped(true);
+
+ // Force creation of the database.
+ Connection lConnection = createConnection();
+ lConnection.close();
+
+ LOGGER.info("Database started: \n URL = " +
+ getExternalJdbcUrl() + "\n user = " + getUsername() +
+ "\n password = " + getPassword());
+
+ createDataSource();
+
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ @Override
+ public void run() {
+ if (isStarted()) {
+ LOGGER.warning("Shutting down db");
+ DerbyDatabase.this.stop();
+ }
+ }
+ });
+ } catch (Exception e) {
+ throw new RuntimeException("Problem starting database", e);
+ }
+ }
+
+ /**
+ * Waits until the database server has started or stopped.
+ *
+ * @param aStarted
+ * If true, waits until the server is up, if false, waits until
+ * the server is down.
+ * @throws InterruptedException
+ */
+ private void waitUntilStartedOrStopped(boolean aStarted)
+ throws InterruptedException {
+ long lWaited = 0;
+
+ while (aStarted != isStarted()) {
+ Thread.sleep(POLL_INTERVAL);
+ lWaited += POLL_INTERVAL;
+
+ if (lWaited > MAX_WAIT_TIME) {
+ throw new RuntimeException(
+ "Derby database did not start within " + MAX_WAIT_TIME +
+ "ms");
+ }
+ }
+ }
+
+ /**
+ * Checks if the database server has started or not.
+ *
+ * @return True if started, false otherwise.
+ */
+ private boolean isStarted() {
+ try {
+ getControl().ping();
+
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ /**
+ * Gets the controller for the database server.
+ *
+ * @return Controller.
+ * @throws Exception
+ */
+ private NetworkServerControl getControl() throws Exception {
+ return new NetworkServerControl();
+ }
+
+ /**
+ * Runs the database.
+ *
+ */
+ private void runDatabase() {
+ try {
+ getControl().start(new PrintWriter(System.out));
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.wamblee.persistence.Database#getJdbcUrl()
+ */
+ public String getJdbcUrl() {
+ return getBaseJdbcUrl() +
+ ";create=true;retrieveMessagesFromServerOnGetMessage=true;";
+ }
+
+ private String getBaseJdbcUrl() {
+ return (inmemory ? "jdbc:derby:memory:" : "jdbc:derby:") +
+ DATABASE_NAME;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.wamblee.persistence.Database#getExternalJdbcUrl()
+ */
+ public String getExternalJdbcUrl() {
+ return "jdbc:derby://localhost:1527/" + (inmemory ? "memory:" : "") +
+ DATABASE_NAME;
+ }
+
+ /**
+ * Shuts down the derby database and cleans up all created files.
+ *
+ */
+ private void shutdownDerby() {
+ try {
+ DriverManager.getConnection("jdbc:derby:;shutdown=true");
+ throw new RuntimeException("Derby did not shutdown, "
+ + " should always throw exception at shutdown");
+ } catch (Exception e) {
+ LOGGER.info("Derby has been shut down.");
+ }
+ }
+
+ /**
+ * Gets the user name.
+ */
+ public String getUsername() {
+ return USERNAME;
+ }
+
+ /**
+ * Gets the password.
+ *
+ * @return
+ */
+ public String getPassword() {
+ return PASSWORD;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.wamblee.persistence.Database#createConnection()
+ */
+ public Connection createConnection() throws SQLException {
+ Connection c = DriverManager.getConnection(getJdbcUrl(), getUsername(),
+ getPassword());
+
+ return c;
+ }
+
+ /**
+ * Stops the derby database and cleans up all derby files.
+ */
+ public void doStop() {
+ try {
+ // shutdown network server.
+ getControl().shutdown();
+ waitUntilStartedOrStopped(false);
+
+ // shutdown inmemory access.
+ shutdownDerby();
+ cleanPersistentStorage();
+ } catch (Exception e) {
+ LOGGER.log(Level.WARNING, "Problem stopping database", e);
+ }
+ }
+
+ /**
+ * Cleans up persistent storage of Derby.
+ */
+ private void cleanPersistentStorage() {
+ File lFile = new File(DATABASE_PATH);
+
+ if (lFile.isFile()) {
+ TestCase.fail("A regular file by the name " + DATABASE_PATH +
+ " exists, clean this up first");
+ }
+
+ if (!lFile.isDirectory()) {
+ return; // no-op already cleanup up.
+ }
+ FileSystemUtils.deleteDirRecursively(DATABASE_PATH);
+ }
}
import java.util.Arrays;
import java.util.List;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
/**
* Capabilities of this type of database.
*/
- public static final List<String> CAPABILIITIES = Arrays.asList(DatabaseProvider.CAPABILITY_IN_MEMORY,
- "DERBY");
+ public static final List<String> CAPABILIITIES = Arrays.asList(
+ DatabaseProvider.CAPABILITY_IN_MEMORY, "DERBY");
-/**
+ /**
* Creates a new DerbyDatabaseProvider object.
*/
public DerbyDatabaseProvider() {
// Empty
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public Database create() {
return new DerbyDatabase();
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
public DatabaseDescription getDescription() {
return new DatabaseDescription(CAPABILIITIES.toArray(new String[0]),
"Derby", "In-memory, volatile, set breakpoint to debug");
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
protected List<String> getCapabilities() {
return CAPABILIITIES;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
- * Database that encapsulates connection to an external database.
- * Database connection details can be configured through system properties
- * and environment variables, see {@link #DB_URL_PROP}, {@link #DB_USER_PROP}, and
- * {@link #DB_PASSWORD_PROP|.
+ * Database that encapsulates connection to an external database. Database
+ * connection details can be configured through system properties and
+ * environment variables, see {@link #DB_URL_PROP}, {@link #DB_USER_PROP}, and
+ * {@link #DB_PASSWORD_PROP|.
*
- * This class assumes modern database drivers that work together with java.util.ServiceLoader
- * so that explicitly doing a Class.forName() is not necessary to load the database driver.
+ * This class assumes modern database drivers that work together with
+ * java.util.ServiceLoader so that explicitly doing a Class.forName() is not
+ * necessary to load the database driver.
*/
public class ExternalDatabase extends AbstractDatabase {
-
- private static final Logger LOGGER = Logger.getLogger(ExternalDatabase.class.getName());
-
- /**
- * System property/environment variable that defines the database URL.
- */
- public static final String DB_URL_PROP = "TEST_DB_URL";
-
- /**
- * System property/environment variable that defines the database user.
- */
- public static final String DB_USER_PROP = "TEST_DB_USER";
-
- /**
- * System property/environment variable that defines the database password.
- */
- public static final String DB_PASSWORD_PROP = "TEST_DB_PASSWORD";
-
-
- private String itsUrl;
- private String itsUser;
- private String itsPassword;
-
- private DataSource itsDataSource;
-
- public ExternalDatabase() {
- // Empty
- }
-
- public String getExternalJdbcUrl() {
- return itsUrl;
- }
-
- public String getJdbcUrl() {
- return itsUrl;
- }
-
- public String getPassword() {
- return itsPassword;
- }
-
- public String getUsername() {
- return itsUser;
- }
-
- public void doStart() {
- itsUrl = getProperty(DB_URL_PROP);
- itsUser = getProperty(DB_USER_PROP);
- itsPassword = getProperty(DB_PASSWORD_PROP);
-
- createDataSource();
- }
-
- public void doStop() {
- // Empty.
- }
+
+ private static final Logger LOGGER = Logger
+ .getLogger(ExternalDatabase.class.getName());
+
+ /**
+ * System property/environment variable that defines the database URL.
+ */
+ public static final String DB_URL_PROP = "TEST_DB_URL";
+
+ /**
+ * System property/environment variable that defines the database user.
+ */
+ public static final String DB_USER_PROP = "TEST_DB_USER";
+
+ /**
+ * System property/environment variable that defines the database password.
+ */
+ public static final String DB_PASSWORD_PROP = "TEST_DB_PASSWORD";
+
+ private String itsUrl;
+ private String itsUser;
+ private String itsPassword;
+
+ private DataSource itsDataSource;
+
+ public ExternalDatabase() {
+ // Empty
+ }
+
+ public String getExternalJdbcUrl() {
+ return itsUrl;
+ }
+
+ public String getJdbcUrl() {
+ return itsUrl;
+ }
+
+ public String getPassword() {
+ return itsPassword;
+ }
+
+ public String getUsername() {
+ return itsUser;
+ }
+
+ public void doStart() {
+ itsUrl = getProperty(DB_URL_PROP);
+ itsUser = getProperty(DB_USER_PROP);
+ itsPassword = getProperty(DB_PASSWORD_PROP);
+
+ createDataSource();
+ }
+
+ public void doStop() {
+ // Empty.
+ }
}
public class ExternalDatabaseProvider extends AbstractDatabaseProvider {
- /**
- * Capabilities of this type of database.
- */
- public static final List<String> CAPABILIITIES = Arrays
- .asList(CAPABILITY_EXTERNAL);
+ /**
+ * Capabilities of this type of database.
+ */
+ public static final List<String> CAPABILIITIES = Arrays
+ .asList(CAPABILITY_EXTERNAL);
- @Override
- protected List<String> getCapabilities() {
- return CAPABILIITIES;
- }
+ @Override
+ protected List<String> getCapabilities() {
+ return CAPABILIITIES;
+ }
- public Database create() {
- return new ExternalDatabase();
- }
+ public Database create() {
+ return new ExternalDatabase();
+ }
- public DatabaseDescription getDescription() {
- return new DatabaseDescription(
- CAPABILIITIES.toArray(new String[0]),
- "External Database",
- "Any database as described by the JDBC URL: requires system properties or environment variables: "
- + ExternalDatabase.DB_URL_PROP
- + ", "
- + ExternalDatabase.DB_USER_PROP
- + ", and "
- + ExternalDatabase.DB_PASSWORD_PROP);
- }
+ public DatabaseDescription getDescription() {
+ return new DatabaseDescription(
+ CAPABILIITIES.toArray(new String[0]),
+ "External Database",
+ "Any database as described by the JDBC URL: requires system properties or environment variables: " +
+ ExternalDatabase.DB_URL_PROP +
+ ", " +
+ ExternalDatabase.DB_USER_PROP +
+ ", and " +
+ ExternalDatabase.DB_PASSWORD_PROP);
+ }
}
import org.wamblee.support.jndi.StubInitialContextFactory;
-
/**
* Utility for building an appropriately configured EntityManagerFactory. The
* idea is that a persistence.xml is used unchanged from the production version.
*/
public class JpaBuilder {
- private static final Logger LOGGER = Logger.getLogger(JpaBuilder.class
- .getName());
+ private static final Logger LOGGER = Logger.getLogger(JpaBuilder.class
+ .getName());
+
+ /**
+ * Callback interface to execute some JPA code within a transaction with the
+ * entitymanager to use provided as input.
+ */
+ public static interface JpaUnitOfWork<T> {
+ /**
+ * Executes the unit of work. A transaction has been started.
+ *
+ * @param em
+ * Entity manager.
+ * @return Result of the execute method. If you don't want to return
+ * anything use <code>Void</code> for the return type and return
+ * null from the implementation.
+ */
+ T execute(EntityManager em);
+ }
+
+ private PersistenceUnitDescription persistenceUnit;
+ private DataSource dataSource;
+ private EntityManagerFactory factory;
+
+ /**
+ * Constructs the builder.
+ *
+ * @param aDataSource
+ * Datasource of database.
+ * @param aPersistenceUnit
+ * Persistence unit.
+ */
+ public JpaBuilder(DataSource aDataSource,
+ PersistenceUnitDescription aPersistenceUnit) {
+ persistenceUnit = aPersistenceUnit;
+ dataSource = aDataSource;
+ StubInitialContextFactory.register();
+ }
- /**
- * Callback interface to execute some JPA code within a transaction with the
- * entitymanager to use provided as input.
- */
- public static interface JpaUnitOfWork<T> {
- /**
- * Executes the unit of work. A transaction has been started.
- * @param em Entity manager.
- * @return Result of the execute method. If you don't want to return anything use
- * <code>Void</code> for the return type and return null from the implementation.
- */
- T execute(EntityManager em);
- }
+ /**
+ * Starts the builder, which in particular, mocks JNDI, binds the datasource
+ * the JNDI where the persistence unit expects it, creates the entity
+ * manager factory, and forces creation of the database schema.
+ */
+ public void start() throws Exception {
+ try {
+ InitialContext ctx = new InitialContext();
+ ctx.bind(persistenceUnit.getJndiName(), dataSource);
+ } catch (NamingException e) {
+ throw new RuntimeException("JNDI problem", e);
+ }
+ factory = createFactory();
+ execute(new JpaUnitOfWork<Void>() {
+ public Void execute(EntityManager em) {
+ // Empty, just to trigger database schema creation.
+ return null;
+ }
+ });
+ }
- private PersistenceUnitDescription persistenceUnit;
- private DataSource dataSource;
- private EntityManagerFactory factory;
+ /**
+ * Stops the entity manager factory and disables JNDI mocking.
+ */
+ public void stop() {
+ StubInitialContextFactory.unregister();
+ factory.close();
+ }
- /**
- * Constructs the builder.
- *
- * @param aDataSource
- * Datasource of database.
- * @param aPersistenceUnit
- * Persistence unit.
- */
- public JpaBuilder(DataSource aDataSource,
- PersistenceUnitDescription aPersistenceUnit) {
- persistenceUnit = aPersistenceUnit;
- dataSource = aDataSource;
- StubInitialContextFactory.register();
- }
+ /**
+ * Creates a new entity manager factory. Typically not used by test code.
+ *
+ * @return Entity manager factory.
+ */
+ public EntityManagerFactory createFactory() {
+ Map<String, String> jpaProps = new TreeMap<String, String>();
- /**
- * Starts the builder, which in particular, mocks JNDI, binds the datasource
- * the JNDI where the persistence unit expects it, creates the entity
- * manager factory, and forces creation of the database schema.
- */
- public void start() throws Exception {
- try {
- InitialContext ctx = new InitialContext();
- ctx.bind(persistenceUnit.getJndiName(), dataSource);
- } catch (NamingException e) {
- throw new RuntimeException("JNDI problem", e);
- }
- factory = createFactory();
- execute(new JpaUnitOfWork<Void>() {
- public Void execute(EntityManager em) {
- // Empty, just to trigger database schema creation.
- return null;
- }
- });
- }
+ JpaCustomizerBuilder.getCustomizer().customize(persistenceUnit,
+ jpaProps);
- /**
- * Stops the entity manager factory and disables JNDI mocking.
- */
- public void stop() {
- StubInitialContextFactory.unregister();
- factory.close();
- }
+ // jpaProps.put("javax.persistence.provider",
+ // HibernatePersistence.class.getName());
+ EntityManagerFactory factory = Persistence.createEntityManagerFactory(
+ persistenceUnit.getUnitName(), jpaProps);
- /**
- * Creates a new entity manager factory. Typically not used by test code.
- * @return Entity manager factory.
- */
- public EntityManagerFactory createFactory() {
- Map<String, String> jpaProps = new TreeMap<String, String>();
-
- JpaCustomizerBuilder.getCustomizer().customize(persistenceUnit, jpaProps);
-
- //jpaProps.put("javax.persistence.provider", HibernatePersistence.class.getName());
- EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnit
- .getUnitName(), jpaProps);
-
- LOGGER.info("Using " + factory.getClass());
- return factory;
- }
+ LOGGER.info("Using " + factory.getClass());
+ return factory;
+ }
- /**
- * Executes a unit of work. This creates an entitymanager and runs the
- * {@link JpaUnitOfWork#execute(EntityManager)} within a transaction, passing
- * it the entity manager. Use of this method saves a lot of typing for applications.
- *
- * @param aWork Work to execute.
- * @return The return value of the execute method of the unit of work.
- */
- public <T> T execute(JpaUnitOfWork<T> aWork) throws Exception {
- EntityManager em = factory.createEntityManager();
- EntityTransaction transaction = em.getTransaction();
- transaction.begin();
- try {
- T value = aWork.execute(em);
- transaction.commit();
- return value;
- } catch (Exception e) {
- LOGGER.log(Level.WARNING, "Exception occured", e);
- transaction.rollback();
- throw e;
- } finally {
- em.close();
- }
- }
+ /**
+ * Executes a unit of work. This creates an entitymanager and runs the
+ * {@link JpaUnitOfWork#execute(EntityManager)} within a transaction,
+ * passing it the entity manager. Use of this method saves a lot of typing
+ * for applications.
+ *
+ * @param aWork
+ * Work to execute.
+ * @return The return value of the execute method of the unit of work.
+ */
+ public <T> T execute(JpaUnitOfWork<T> aWork) throws Exception {
+ EntityManager em = factory.createEntityManager();
+ EntityTransaction transaction = em.getTransaction();
+ transaction.begin();
+ try {
+ T value = aWork.execute(em);
+ transaction.commit();
+ return value;
+ } catch (Exception e) {
+ LOGGER.log(Level.WARNING, "Exception occured", e);
+ transaction.rollback();
+ throw e;
+ } finally {
+ em.close();
+ }
+ }
}
import org.dbunit.dataset.filter.ITableFilterSimple;
/**
- * JPA customizer is used to customize properties for a given JPA implementation.
+ * JPA customizer is used to customize properties for a given JPA
+ * implementation.
*
- * Implementations of JpaCustomizer are found using {@link ServiceLoader}. In case
- * of testing with a specific JPA provider, the customizer library for that JPA provider
- * must be on the classpath as well.
+ * Implementations of JpaCustomizer are found using {@link ServiceLoader}. In
+ * case of testing with a specific JPA provider, the customizer library for that
+ * JPA provider must be on the classpath as well.
*
* @author Erik Brakkee
*/
public interface JpaCustomizer {
- void customize(PersistenceUnitDescription aPersistenceUnit, Map<String,String> aJpaProperties);
-
+ void customize(PersistenceUnitDescription aPersistenceUnit,
+ Map<String, String> aJpaProperties);
+
ITableFilterSimple getJpaTables();
}
public class JpaCustomizerBuilder {
- private static final ServiceLoader<JpaCustomizer> CUSTOMIZERS =
- ServiceLoader.load(JpaCustomizer.class);
-
-
- public static JpaCustomizer getCustomizer() {
- List<JpaCustomizer> customizers = new ArrayList<JpaCustomizer>();
- for (JpaCustomizer customizer: CUSTOMIZERS) {
+ private static final ServiceLoader<JpaCustomizer> CUSTOMIZERS = ServiceLoader
+ .load(JpaCustomizer.class);
+
+ public static JpaCustomizer getCustomizer() {
+ List<JpaCustomizer> customizers = new ArrayList<JpaCustomizer>();
+ for (JpaCustomizer customizer : CUSTOMIZERS) {
customizers.add(customizer);
}
return new CompositeJpaCustomizer(customizers);
import org.dbunit.IDatabaseTester;
/**
- * This class is the entry point for JPA tests. Test code should construct a JpaTester in the
- * <code>@Before</code> method and call {@link #start()} on it in that method. Also, test code should
- * call {@link #stop()} on it in the <code>@After</code> method.
+ * This class is the entry point for JPA tests. Test code should construct a
+ * JpaTester in the <code>@Before</code> method and call {@link #start()} on it
+ * in that method. Also, test code should call {@link #stop()} on it in the
+ * <code>@After</code> method.
*
- * This class is constructed with a description of the persistence unit to be tested. The principle is that
- * an existing <code>persistence.xml</code> can be tested without change in unit test code.
- *
- * It then takes care of the following:
- * <ul>
- * <li> Creating an inmemory database for testing (default) or connecting to an external database.
- * See {@link DatabaseBuilder} for more information on how a databse is obtained.
- * </li>
- * <li> Drop all database tables that are related to the persistence unit under test, including JPA provider
- * specific tables.
- * </li>
- * <li> Creating a datasource for the database and make the datasource available through JNDI.
- * </li>
- * <li> Creating the entity manager factory for JPA and configuring it in such a way that schema creation
- * happens. (Typically, schema creation will be disabled in the persistence.xml but this utility enables it
- * for unit test).
- * </li>
- * <li> Creating a DBUnit database tester which is appropriately configured for the persistence unit under test.
- * </li>
+ * This class is constructed with a description of the persistence unit to be
+ * tested. The principle is that an existing <code>persistence.xml</code> can be
+ * tested without change in unit test code.
+ *
+ * It then takes care of the following:
+ * <ul>
+ * <li>Creating an inmemory database for testing (default) or connecting to an
+ * external database. See {@link DatabaseBuilder} for more information on how a
+ * databse is obtained.</li>
+ * <li>Drop all database tables that are related to the persistence unit under
+ * test, including JPA provider specific tables.</li>
+ * <li>Creating a datasource for the database and make the datasource available
+ * through JNDI.</li>
+ * <li>Creating the entity manager factory for JPA and configuring it in such a
+ * way that schema creation happens. (Typically, schema creation will be
+ * disabled in the persistence.xml but this utility enables it for unit test).</li>
+ * <li>Creating a DBUnit database tester which is appropriately configured for
+ * the persistence unit under test.</li>
* </ul>
*
- * The main entry point for all this functionality is the {@link PersistenceUnitDescription} which describes the
- * persistence unit and must be provided at construction of the <code>JpaTester</code>
+ * The main entry point for all this functionality is the
+ * {@link PersistenceUnitDescription} which describes the persistence unit and
+ * must be provided at construction of the <code>JpaTester</code>
*
- * NOTE: Persistence XML files should be explicitly configured with the classes that are part of the persistence unit
- * since scanning of classes does not work correctly in a unit test environment. This is currently the only limitation.
+ * NOTE: Persistence XML files should be explicitly configured with the classes
+ * that are part of the persistence unit since scanning of classes does not work
+ * correctly in a unit test environment. This is currently the only limitation.
*/
public class JpaTester {
- private PersistenceUnitDescription persistenceUnit;
- private Database db;
- private DataSource dataSource;
- private DatabaseUtils dbUtils;
- private JpaBuilder jpaBuilder;
- private IDatabaseTester dbTester;
-
- /**
- * Constructs the tester.
- * @param aPersistenceUnit Persistence unit under test.
- */
- public JpaTester(PersistenceUnitDescription aPersistenceUnit) {
- persistenceUnit = aPersistenceUnit;
- }
-
- /**
- * Starts the tester. This must be called prior to running the test.
- * @throws Exception
- */
- public void start() throws Exception {
- db = DatabaseBuilder.getDatabase();
- dataSource = db.start();
-
- dbUtils = new DatabaseUtils(dataSource, persistenceUnit.getTables());
- dbUtils.dropTables();
- dbUtils.dropTables(JpaCustomizerBuilder.getCustomizer().getJpaTables());
-
- jpaBuilder = new JpaBuilder(dataSource, persistenceUnit);
- jpaBuilder.start();
-
- // db tester should be created after Jpa builder because jpa builder
- // creates the
- // tables that the tester looks at when it is initialized.
- dbTester = dbUtils.createDbTester();
- }
-
- /**
- * Stops the tester. This must be called after the test.
- */
- public void stop() {
- if (jpaBuilder != null) {
- jpaBuilder.stop();
- }
- if (db != null) {
- db.stop();
- }
- }
-
- public Database getDb() {
- return db;
- }
-
- public DataSource getDataSource() {
- return dataSource;
- }
-
- public IDatabaseTester getDbTester() {
- return dbTester;
- }
-
- public DatabaseUtils getDbUtils() {
- return dbUtils;
- }
-
- public JpaBuilder getJpaBuilder() {
- return jpaBuilder;
- }
-
- public PersistenceUnitDescription getPersistenceUnit() {
- return persistenceUnit;
- }
+ private PersistenceUnitDescription persistenceUnit;
+ private Database db;
+ private DataSource dataSource;
+ private DatabaseUtils dbUtils;
+ private JpaBuilder jpaBuilder;
+ private IDatabaseTester dbTester;
+
+ /**
+ * Constructs the tester.
+ *
+ * @param aPersistenceUnit
+ * Persistence unit under test.
+ */
+ public JpaTester(PersistenceUnitDescription aPersistenceUnit) {
+ persistenceUnit = aPersistenceUnit;
+ }
+
+ /**
+ * Starts the tester. This must be called prior to running the test.
+ *
+ * @throws Exception
+ */
+ public void start() throws Exception {
+ db = DatabaseBuilder.getDatabase();
+ dataSource = db.start();
+
+ dbUtils = new DatabaseUtils(dataSource, persistenceUnit.getTables());
+ dbUtils.dropTables();
+ dbUtils.dropTables(JpaCustomizerBuilder.getCustomizer().getJpaTables());
+
+ jpaBuilder = new JpaBuilder(dataSource, persistenceUnit);
+ jpaBuilder.start();
+
+ // db tester should be created after Jpa builder because jpa builder
+ // creates the
+ // tables that the tester looks at when it is initialized.
+ dbTester = dbUtils.createDbTester();
+ }
+
+ /**
+ * Stops the tester. This must be called after the test.
+ */
+ public void stop() {
+ if (jpaBuilder != null) {
+ jpaBuilder.stop();
+ }
+ if (db != null) {
+ db.stop();
+ }
+ }
+
+ public Database getDb() {
+ return db;
+ }
+
+ public DataSource getDataSource() {
+ return dataSource;
+ }
+
+ public IDatabaseTester getDbTester() {
+ return dbTester;
+ }
+
+ public DatabaseUtils getDbUtils() {
+ return dbUtils;
+ }
+
+ public JpaBuilder getJpaBuilder() {
+ return jpaBuilder;
+ }
+
+ public PersistenceUnitDescription getPersistenceUnit() {
+ return persistenceUnit;
+ }
}
public class PersistenceUnitDescription {
- private String jndiName;
- private String unitName;
- private ITableFilterSimple tables;
-
- public PersistenceUnitDescription(String aJndiName, String aUnitName, ITableFilterSimple aTables) {
- jndiName = aJndiName;
- unitName = aUnitName;
- tables = aTables;
- }
-
- public String getJndiName() {
- return jndiName;
- }
-
- public String getUnitName() {
- return unitName;
- }
-
- public ITableFilterSimple getTables() {
- return tables;
- }
+ private String jndiName;
+ private String unitName;
+ private ITableFilterSimple tables;
+
+ public PersistenceUnitDescription(String aJndiName, String aUnitName,
+ ITableFilterSimple aTables) {
+ jndiName = aJndiName;
+ unitName = aUnitName;
+ tables = aTables;
+ }
+
+ public String getJndiName() {
+ return jndiName;
+ }
+
+ public String getUnitName() {
+ return unitName;
+ }
+
+ public ITableFilterSimple getTables() {
+ return tables;
+ }
}
* </ul>
*/
package org.wamblee.support.persistence;
+
public class StubInitiaContextFactoryTest {
- @Before
- @After
- public void setUp() {
- StubInitialContextFactory.unregister();
- }
-
-
- @Test(expected = NamingException.class)
- public void testLookupNotRegistered() throws Exception {
- InitialContext ctx = new InitialContext();
- ctx.bind("a/b", "hallo");
- }
-
- @Test
- public void testLookup() throws Exception {
- StubInitialContextFactory.register();
-
- InitialContext ctx = new InitialContext();
- ctx.bind("a/b", "hallo");
-
- ctx = new InitialContext();
- Object obj = ctx.lookup("a/b");
-
- assertEquals("hallo", obj);
- }
-
+ @Before
+ @After
+ public void setUp() {
+ StubInitialContextFactory.unregister();
+ }
+
+ @Test(expected = NamingException.class)
+ public void testLookupNotRegistered() throws Exception {
+ InitialContext ctx = new InitialContext();
+ ctx.bind("a/b", "hallo");
+ }
+
+ @Test
+ public void testLookup() throws Exception {
+ StubInitialContextFactory.register();
+
+ InitialContext ctx = new InitialContext();
+ ctx.bind("a/b", "hallo");
+
+ ctx = new InitialContext();
+ Object obj = ctx.lookup("a/b");
+
+ assertEquals("hallo", obj);
+ }
+
}
public class DatabaseBuilderTest {
-
- @Test
- public void testListAvailableDatabases() {
- for (DatabaseDescription description: DatabaseBuilder.getSupportedDatabases()) {
- System.out.println(description);
- }
- }
+ @Test
+ public void testListAvailableDatabases() {
+ for (DatabaseDescription description : DatabaseBuilder
+ .getSupportedDatabases()) {
+ System.out.println(description);
+ }
+ }
}
builder = new JpaBuilder(dataSource, persistenceUnit);
builder.start();
-
+
dbtester = dbutils.createDbTester();
}
import org.wamblee.support.persistence.Database;
import org.wamblee.support.persistence.DatabaseBuilder;
-
public class DerbyDatabaseTest {
- private Database db;
- private DataSource ds;
-
- @Before
- public void setUp() {
- db = DatabaseBuilder.getDatabase();
- ds = db.start();
- }
-
- @After
- public void tearDown() {
- db.stop();
- }
-
- @Test
- public void testConnect() throws Exception {
- Connection conn = ds.getConnection();
- try {
- System.out.println("Database name: " + conn.getMetaData().getDatabaseProductName());
- } finally {
- conn.close();
- }
- }
-
- @Test
- public void testUseASecondTimeInTheSameTestCase() throws Exception {
- testConnect();
- tearDown();
- setUp();
- testConnect();
- }
+ private Database db;
+ private DataSource ds;
+
+ @Before
+ public void setUp() {
+ db = DatabaseBuilder.getDatabase();
+ ds = db.start();
+ }
+
+ @After
+ public void tearDown() {
+ db.stop();
+ }
+
+ @Test
+ public void testConnect() throws Exception {
+ Connection conn = ds.getConnection();
+ try {
+ System.out.println("Database name: " +
+ conn.getMetaData().getDatabaseProductName());
+ } finally {
+ conn.close();
+ }
+ }
+
+ @Test
+ public void testUseASecondTimeInTheSameTestCase() throws Exception {
+ testConnect();
+ tearDown();
+ setUp();
+ testConnect();
+ }
}
public class ExternalDatabaseTest {
- @Test
- public void testExternalDB() throws Exception {
- // Connect to inmemory db using External database class.
-
- Database inmemory = DatabaseBuilder
- .getDatabase(DatabaseProvider.CAPABILITY_IN_MEMORY);
- try {
- inmemory.start();
-
- System.setProperty(ExternalDatabase.DB_URL_PROP, inmemory
- .getExternalJdbcUrl());
- System.setProperty(ExternalDatabase.DB_USER_PROP, inmemory
- .getUsername());
- System.setProperty(ExternalDatabase.DB_PASSWORD_PROP, inmemory
- .getPassword());
-
- Database external = DatabaseBuilder
- .getDatabase(DatabaseProvider.CAPABILITY_EXTERNAL);
- assertTrue(external instanceof ExternalDatabase);
- try {
- DataSource ds = external.start();
- Connection conn = ds.getConnection();
- try {
- System.out.println("Database name: "
- + conn.getMetaData().getDatabaseProductName());
- } finally {
- conn.close();
- }
- } finally {
- external.stop();
- }
- } finally {
- inmemory.stop();
- }
-
- }
+ @Test
+ public void testExternalDB() throws Exception {
+ // Connect to inmemory db using External database class.
+
+ Database inmemory = DatabaseBuilder
+ .getDatabase(DatabaseProvider.CAPABILITY_IN_MEMORY);
+ try {
+ inmemory.start();
+
+ System.setProperty(ExternalDatabase.DB_URL_PROP, inmemory
+ .getExternalJdbcUrl());
+ System.setProperty(ExternalDatabase.DB_USER_PROP, inmemory
+ .getUsername());
+ System.setProperty(ExternalDatabase.DB_PASSWORD_PROP, inmemory
+ .getPassword());
+
+ Database external = DatabaseBuilder
+ .getDatabase(DatabaseProvider.CAPABILITY_EXTERNAL);
+ assertTrue(external instanceof ExternalDatabase);
+ try {
+ DataSource ds = external.start();
+ Connection conn = ds.getConnection();
+ try {
+ System.out.println("Database name: " +
+ conn.getMetaData().getDatabaseProductName());
+ } finally {
+ conn.close();
+ }
+ } finally {
+ external.stop();
+ }
+ } finally {
+ inmemory.stop();
+ }
+
+ }
}
@Table(name = "XYZ_MYENTITY")
public class MyEntity {
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
-
- private String sleuteltje;
- private String value;
-
-
- public MyEntity() {
- // Empty
- }
-
- public MyEntity(String aKey, String aValue) {
- sleuteltje = aKey;
- value = aValue;
- }
-
- public String getKey() {
- return sleuteltje;
- }
-
- public String getValue() {
- return value;
- }
-
-
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ private String sleuteltje;
+ private String value;
+
+ public MyEntity() {
+ // Empty
+ }
+
+ public MyEntity(String aKey, String aValue) {
+ sleuteltje = aKey;
+ value = aValue;
+ }
+
+ public String getKey() {
+ return sleuteltje;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
}
import static junit.framework.Assert.*;
-
/**
- * This class shows an example of how to test an entity using jpa.
+ * This class shows an example of how to test an entity using jpa.
*/
public class MyEntityExampleTestBase {
- // This is the magical object that does all the test setup.
- private JpaTester jpaTester;
-
+ // This is the magical object that does all the test setup.
+ private JpaTester jpaTester;
+
// The jpa tester initializes a lot for us....
-
- // A JPA builder that provides a transaction scoped entity manager for us.
- private JpaBuilder builder;
-
- // The database tester for dbunit which is appropriately configured for our persistence unit.
- private IDatabaseTester dbtester;
-
- // Database utilities with some additional functionality for working with the databse
- // such as dropping tables, cleaning tables, etc.
- private DatabaseUtils dbutils;
-
- @Before
- public void setUp() throws Exception {
-
- // First we create the JpaTester by telling us which persistence unit we are going to test
- jpaTester = new JpaTester(new MyPersistenceUnit());
- jpaTester.start();
-
- // Retrieve some useful objects fromt he jpa tester. It also provides direct access to the datasource
- // but we don't need it. We can use datbase utils if we want to execute straight JDBC calls.
- builder = jpaTester.getJpaBuilder();
- dbtester = jpaTester.getDbTester();
- dbutils = jpaTester.getDbUtils();
- }
-
- @After
- public void tearDown() {
- jpaTester.stop();
- }
-
- @Test
- public void testEntityPersistence() throws Exception {
-
- // Use the JPA builder to create a transaction scoped entity manager for as and execute the
- // unit of work.
- builder.execute(new JpaUnitOfWork<Void>() {
- public Void execute(EntityManager em) {
- MyEntity entity = new MyEntity("a", "b");
- em.persist(entity);
- return null;
- }
- });
-
- // Verify one row is written (using Db unit)
- ITable table = dbtester.getDataSet().getTable("XYZ_MYENTITY");
- assertEquals(1, table.getRowCount());
-
- assertEquals("a", table.getValue(0, "SLEUTELTJE"));
- assertEquals("b", table.getValue(0, "VALUE"));
-
- // For this simple test, it can also be done through DatabaseUtils
- assertEquals(1, dbutils.getTableSize("XYZ_MYENTITY"));
-
- }
+
+ // A JPA builder that provides a transaction scoped entity manager for us.
+ private JpaBuilder builder;
+
+ // The database tester for dbunit which is appropriately configured for our
+ // persistence unit.
+ private IDatabaseTester dbtester;
+
+ // Database utilities with some additional functionality for working with
+ // the databse
+ // such as dropping tables, cleaning tables, etc.
+ private DatabaseUtils dbutils;
+
+ @Before
+ public void setUp() throws Exception {
+
+ // First we create the JpaTester by telling us which persistence unit we
+ // are going to test
+ jpaTester = new JpaTester(new MyPersistenceUnit());
+ jpaTester.start();
+
+ // Retrieve some useful objects fromt he jpa tester. It also provides
+ // direct access to the datasource
+ // but we don't need it. We can use datbase utils if we want to execute
+ // straight JDBC calls.
+ builder = jpaTester.getJpaBuilder();
+ dbtester = jpaTester.getDbTester();
+ dbutils = jpaTester.getDbUtils();
+ }
+
+ @After
+ public void tearDown() {
+ jpaTester.stop();
+ }
+
+ @Test
+ public void testEntityPersistence() throws Exception {
+
+ // Use the JPA builder to create a transaction scoped entity manager for
+ // as and execute the
+ // unit of work.
+ builder.execute(new JpaUnitOfWork<Void>() {
+ public Void execute(EntityManager em) {
+ MyEntity entity = new MyEntity("a", "b");
+ em.persist(entity);
+ return null;
+ }
+ });
+
+ // Verify one row is written (using Db unit)
+ ITable table = dbtester.getDataSet().getTable("XYZ_MYENTITY");
+ assertEquals(1, table.getRowCount());
+
+ assertEquals("a", table.getValue(0, "SLEUTELTJE"));
+ assertEquals("b", table.getValue(0, "VALUE"));
+
+ // For this simple test, it can also be done through DatabaseUtils
+ assertEquals(1, dbutils.getTableSize("XYZ_MYENTITY"));
+
+ }
}
import org.wamblee.support.persistence.PersistenceUnitDescription;
/**
- * This class describes the persistence unit that we are testing.
+ * This class describes the persistence unit that we are testing.
*/
public class MyPersistenceUnit extends PersistenceUnitDescription {
- private static final String JNDI_NAME = "wamblee/support/test";
- private static final String PERSISTENCE_UNIT_NAME = "org.wamblee.jee.support-test";
-
- public MyPersistenceUnit() {
- super(JNDI_NAME, PERSISTENCE_UNIT_NAME, new MyTables());
- }
+ private static final String JNDI_NAME = "wamblee/support/test";
+ private static final String PERSISTENCE_UNIT_NAME = "org.wamblee.jee.support-test";
+
+ public MyPersistenceUnit() {
+ super(JNDI_NAME, PERSISTENCE_UNIT_NAME, new MyTables());
+ }
}
import org.dbunit.dataset.filter.ITableFilterSimple;
/**
- * This class describes the tables we are testing.
- * This implementation selects all tables with the "XYZ" prefix.
+ * This class describes the tables we are testing. This implementation selects
+ * all tables with the "XYZ" prefix.
*/
public class MyTables implements ITableFilterSimple {
-
- /**
- *
- * @param aJpaTables Specific tables used by the JPA provider in addition to those for the
- * entities.
- */
- public MyTables() {
- // Empty.
- }
- public boolean accept(String tableName) throws DataSetException {
- return tableName.startsWith("XYZ_");
- }
+ /**
+ *
+ * @param aJpaTables
+ * Specific tables used by the JPA provider in addition to those
+ * for the entities.
+ */
+ public MyTables() {
+ // Empty.
+ }
+
+ public boolean accept(String tableName) throws DataSetException {
+ return tableName.startsWith("XYZ_");
+ }
}
import java.util.Map;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class HibernateJpaCustomizer implements JpaCustomizer {
-/**
+ /**
* Creates a new HibernateJpaCustomizer object.
*/
public HibernateJpaCustomizer() {
// Empty
}
- /**
- * DOCUMENT ME!
- *
- * @param aPersistenceUnit DOCUMENT ME!
- * @param aJpaProperties DOCUMENT ME!
- */
@Override
public void customize(PersistenceUnitDescription aPersistenceUnit,
Map<String, String> aJpaProperties) {
// Hibernate: Override transaction type and datasource
- aJpaProperties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
+ aJpaProperties.put("javax.persistence.transactionType",
+ "RESOURCE_LOCAL");
aJpaProperties.put("javax.persistence.jtaDataSource", null);
aJpaProperties.put("javax.persistence.nonJtaDataSource",
aPersistenceUnit.getJndiName());
aJpaProperties.put("hibernate.hbm2ddl.auto", "create");
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public ITableFilterSimple getJpaTables() {
return new HibernateTables();
import java.util.Arrays;
import java.util.List;
-
/**
* Toplink-specific tables.
*/
public class HibernateTables implements ITableFilterSimple {
- /**
- * DOCUMENT ME!
- */
- private static final List<String> TABLES = Arrays.asList(new String[] { "" });
+ private static final List<String> TABLES = Arrays
+ .asList(new String[] { "" });
- /**
- * DOCUMENT ME!
- *
- * @param aTableName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws DataSetException DOCUMENT ME!
- */
public boolean accept(String aTableName) throws DataSetException {
return TABLES.contains(aTableName);
}
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
import javax.sql.DataSource;
-
/**
- * This class shows an example of how to test an entity using jpa.
+ * This class shows an example of how to test an entity using jpa.
*/
public class MyEntityExampleTest extends MyEntityExampleTestBase {
// Empty, all tests are inherited
import javax.naming.Context;
import javax.naming.InitialContext;
-
/**
- * See
- * http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use
- * for clients that would like to use a JTA SE pu instead of a RESOURCE_LOCAL
- * SE pu. This utility also makes sure that using a persistence.xml with a
- * JTA datasource works in a standalone Java SE environment together with our
- * JNDI stub.
+ * See http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG)
+ * Use for clients that would like to use a JTA SE pu instead of a
+ * RESOURCE_LOCAL SE pu. This utility also makes sure that using a
+ * persistence.xml with a JTA datasource works in a standalone Java SE
+ * environment together with our JNDI stub.
*/
public class JndiSessionCustomizer implements SessionCustomizer {
-/**
+ /**
* Creates a new JndiSessionCustomizer object.
*/
public JndiSessionCustomizer() {
/**
* Get a dataSource connection and set it on the session with
* lookupType=STRING_LOOKUP
- *
- * @param session DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
+ *
+ *
*/
public void customize(Session session) throws Exception {
JNDIConnector connector = null;
- Context context = null;
+ Context context = null;
try {
context = new InitialContext();
if (null != context) {
- connector = (JNDIConnector) session.getLogin().getConnector(); // possible CCE
- // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
- // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in
- // the COMPOSITE_NAME_LOOKUP being set
- // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
+ connector = (JNDIConnector) session.getLogin().getConnector(); // possible
+ // CCE
+ // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
+ // Note: if both jta and non-jta elements exist this will only
+ // change the first one - and may still result in
+ // the COMPOSITE_NAME_LOOKUP being set
+ // Make sure only jta-data-source is in persistence.xml with no
+ // non-jta-data-source property set
connector.setLookupType(JNDIConnector.STRING_LOOKUP);
- // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
- JNDIConnector writeConnector = (JNDIConnector) session.getLogin()
- .getConnector();
+ // Or, if you are specifying both JTA and non-JTA in your
+ // persistence.xml then set both connectors to be safe
+ JNDIConnector writeConnector = (JNDIConnector) session
+ .getLogin().getConnector();
writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
- JNDIConnector readConnector = (JNDIConnector) ((DatabaseLogin) ((ServerSession) session).getReadConnectionPool()
- .getLogin()).getConnector();
+ JNDIConnector readConnector = (JNDIConnector) ((DatabaseLogin) ((ServerSession) session)
+ .getReadConnectionPool().getLogin()).getConnector();
readConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
- System.out.println("JndiSessionCustomizer: configured "
- + connector.getName());
+ System.out.println("JndiSessionCustomizer: configured " +
+ connector.getName());
} else {
throw new Exception("JndiSessionCustomizer: Context is null");
}
import java.util.Map;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
public class ToplinkJpaCustomizer implements JpaCustomizer {
-/**
+ /**
* Creates a new ToplinkJpaCustomizer object.
*/
public ToplinkJpaCustomizer() {
// Empty
}
- /**
- * DOCUMENT ME!
- *
- * @param aPersistenceUnit DOCUMENT ME!
- * @param aJpaProperties DOCUMENT ME!
- */
@Override
public void customize(PersistenceUnitDescription aPersistenceUnit,
Map<String, String> aJpaProperties) {
aJpaProperties.put("toplink.ddl-generation", "create-tables");
}
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
@Override
public ITableFilterSimple getJpaTables() {
return new ToplinkTables();
import java.util.Arrays;
import java.util.List;
-
/**
* Toplink-specific tables.
*/
public class ToplinkTables implements ITableFilterSimple {
- /**
- * DOCUMENT ME!
- */
- private static final List<String> TABLES = Arrays.asList(new String[] {
- "SEQUENCE"
- });
+ private static final List<String> TABLES = Arrays
+ .asList(new String[] { "SEQUENCE" });
- /**
- * DOCUMENT ME!
- *
- * @param aTableName DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws DataSetException DOCUMENT ME!
- */
public boolean accept(String aTableName) throws DataSetException {
return TABLES.contains(aTableName);
}
import javax.sql.DataSource;
-
/**
- * DOCUMENT ME!
- *
+ *
* @author $author$
* @version $Revision$
*/
import javax.sql.DataSource;
-
/**
- * This class shows an example of how to test an entity using jpa.
+ * This class shows an example of how to test an entity using jpa.
*/
public class MyEntityExampleTest extends MyEntityExampleTestBase {
// Empty, all tests are inherited